How to Compare two objects in unit test?

前端 未结 15 1704
自闭症患者
自闭症患者 2020-11-30 03:15
public class Student
{
    public string Name { get; set; }
    public int ID { get; set; }
}

...

var st1 = new Student
{
    ID =          


        
15条回答
  •  情话喂你
    2020-11-30 03:29

    If you use NUnit you may using this syntax and specify an IEqualityComparer specifically for the test:

    [Test]
    public void CompareObjectsTest()
    {
        ClassType object1 = ...;
        ClassType object2 = ...;
        Assert.That( object1, Is.EqualTo( object2 ).Using( new MyComparer() ) );
    }
    
    private class MyComparer : IEqualityComparer
    {
        public bool Equals( ClassType x, ClassType y )
        {
            return ....
        }
    
        public int GetHashCode( ClassType obj )
        {
            return obj.GetHashCode();
        }
    }
    

    See also here: Equal Constraint (NUnit 2.4 / 2.5)

提交回复
热议问题