我有两个相同类型的对象需要比较,但objectA上的一个对象属性的值应该等于objectB上不同名称的属性。
鉴于我的目标:
class MyObject
{
public string Alpha {get; set;}
public string Beta {get; set;}
}
var expected = new MyObject {"string1", "string1"};
var actual = new MyObject {"string1", null};
我需要验证actual.Alpha == expected.Alpha 和actual.Beta == expected.Alpha
可以这样做吗?
答案 0 :(得分:1)
我认为你想要这样的东西:
// VS Unit Testing Framework
Assert.IsTrue(actual.Alpha == expected.Alpha, "the Alpha objects are not equals");
Assert.IsTrue(actual.Beta == expected.Beta, "the Beta objects are not equals");
// Fluent Assertion
actual.Alpha.Should().Be(expected.Alpha);
actual.Beta.Should().Be(expected.Beta);
另外,如果你想比较对象列表
// Helper method to compare - VS Unit Testing Framework
private static void CompareIEnumerable<T>(IEnumerable<T> one, IEnumerable<T> two, Func<T, T, bool> comparisonFunction)
{
var oneArray = one as T[] ?? one.ToArray();
var twoArray = two as T[] ?? two.ToArray();
if (oneArray.Length != twoArray.Length)
{
Assert.Fail("Collections have not same length");
}
for (int i = 0; i < oneArray.Length; i++)
{
var isEqual = comparisonFunction(oneArray[i], twoArray[i]);
Assert.IsTrue(isEqual);
}
}
public void HowToCall()
{
// How you need to call the comparer helper:
CompareIEnumerable(actual, expected, (x, y) =>
x.Alpha == y.Alpha &&
x.Beta == y.Beta );
}