Skip to content

Instantly share code, notes, and snippets.

@jburditt
Last active May 24, 2016 23:12
Show Gist options
  • Save jburditt/3778815c3ad6fde5ae35d5f91e16e9f0 to your computer and use it in GitHub Desktop.
Save jburditt/3778815c3ad6fde5ae35d5f91e16e9f0 to your computer and use it in GitHub Desktop.
Assert Helper Functions e.g. Test Object fields
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));
}
}
}
[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);
}
}
@jburditt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment