Last active
May 24, 2016 23:12
-
-
Save jburditt/3778815c3ad6fde5ae35d5f91e16e9f0 to your computer and use it in GitHub Desktop.
Assert Helper Functions e.g. Test Object fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
//http://stackoverflow.com/questions/23530982/c-sharp-asserting-two-objects-are-equal-in-unit-tests | |
namespace Tests.Helpers | |
{ | |
public class AssertHelper | |
{ | |
public static void HasEqualFieldValues<T>(T expected, T actual) | |
{ | |
var failures = new List<string>(); | |
var fields = typeof(T).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); | |
foreach (var field in fields) | |
{ | |
var v1 = field.GetValue(expected); | |
var v2 = field.GetValue(actual); | |
if (v1 == null && v2 == null) continue; | |
if (!v1.Equals(v2)) failures.Add($"{field.Name}: Expected:<{v1}> Actual:<{v2}>"); | |
} | |
if (failures.Count > 0) | |
Assert.Fail("AssertHelper.HasEqualFieldValues failed. " + Environment.NewLine + string.Join(Environment.NewLine, failures)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestClass] | |
public class AssertHelperTests | |
{ | |
[TestMethod] | |
[ExpectedException(typeof(AssertFailedException))] | |
public void ShouldFailForDifferentClasses() | |
{ | |
var actual = new NewPaymentEntry() { acct = "1" }; | |
var expected = new NewPaymentEntry() { acct = "2" }; | |
AssertHelper.HasEqualFieldValues(expected, actual); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copied without permission from:
http://stackoverflow.com/questions/23530982/c-sharp-asserting-two-objects-are-equal-in-unit-tests