如何在单元测试中比较两个对象?

63
public class Student
{
    public string Name { get; set; }
    public int ID { get; set; }
}

...

var st1 = new Student
{
    ID = 20,
    Name = "ligaoren",
};

var st2 = new Student
{
    ID = 20,
    Name = "ligaoren",
};

Assert.AreEqual<Student>(st1, st2);// How to Compare two object in Unit test?

如何在单元测试中比较两个集合?


你是在询问比较对象的相等性并测试对象是否等效吗? - Intrigue
17个回答

1
如果您使用NUnit,您可以使用这种语法并为测试指定一个特定的IEqualityComparer
[Test]
public void CompareObjectsTest()
{
    ClassType object1 = ...;
    ClassType object2 = ...;
    Assert.That( object1, Is.EqualTo( object2 ).Using( new MyComparer() ) );
}

private class MyComparer : IEqualityComparer<ClassType>
{
    public bool Equals( ClassType x, ClassType y )
    {
        return ....
    }

    public int GetHashCode( ClassType obj )
    {
        return obj.GetHashCode();
    }
}

此外还可以参考这里: 等式约束 (NUnit 2.4 / 2.5)


1

我想添加另一个由Mark Seeman发布的答案版本。

在我的代码中,我使用了Mark Seeman的SemanticComparison Nuget包(过去这个Nuget包是AutoFixture包的一部分,但现在它独立存在)。

该软件包允许编写像下面示例中“Assert”部分中的代码一样,其中我比较actualInstanceexpectedInstance,它们都是DataClass类型。

在示例中,我添加了一个可选步骤,使用Without方法比较两个DataClass实例时排除ID属性。

    [Test]
    public void CompareInstances_Test()
    {
        // Arrange: Instanciate a class the represents the instance with the properties you expect
        DataClass expectedInstance = new DataClass();
        // Set properties here


        // Act: Call a method in the tested class that will produce the result you want to compare to
        var subjectUnderTest = new SubjectUnderTest();
        DataClass actualInstance = subjectUnderTest.CreateInstance();


        // Assert: Compare the two instances, but ignore the "ID" property
        expectedInstance.AsSource().OfLikeness<DataClass>().Without(x => x.ID).ShouldEqual(actualInstance);
    }

0
这是我所做的事情:
public static void AreEqualXYZ_UsageExample()
{
    AreEqualXYZ(actual: class1UnderTest, 
        expectedBoolExample: true, 
        class2Assert: class2 => Assert.IsNotNull(class2), 
        class3Assert: class3 => Assert.AreEqual(42, class3.AnswerToEverything));
}

public static void AreEqualXYZ(Class1 actual,
    bool expectedBoolExample,
    Action<Class2> class2Assert,
    Action<Class3> class3Assert)
{
    Assert.AreEqual(actual.BoolExample, expectedBoolExample);

    class2Assert(actual.Class2Property);
    class3Assert(actual.Class3Property);
}

HTH..


0
在 .Net 6 中,建议使用 System.Text.Json 将任何对象序列化为字符串。
这样,您将不需要任何额外的 NuGet 包。
函数 GetConfigurationGetMock 都返回相同对象的实例。
示例写在 XUnit 中 - 但核心代码应该适用于任何测试项目:
[Fact]
public void CompareConfig()
{
    var response = GetConfiguration();
    var mock = GetMock();

    string result = JsonSerializer.Serialize(response);
    string expectedResult = JsonSerializer.Serialize(mock);

    Assert.Equal(expectedResult, result);
}

0

只需使用这个方法,它将检查并返回成功的结果,如果您的类实例相同。不是您的类引用类型。干杯 :)

private fun verifyYourObject(obj1: YourClass, clazz: Class<*>) {
        assertNotNull(obj1)
        assertThat(obj1, instanceOf(clazz))
    }

-1
也许你需要在这个类中添加一个 public bool Equals(object o) 方法。

-4
obj1.ToString().Equals(obj2.ToString())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接