How to Compare two objects in unit test?

前端 未结 15 1593
自闭症患者
自闭症患者 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:21
    1. Hello firstly add your test project Newtonsoft.Json with Nuget PM

      PM> Install-Package Newtonsoft.Json -Version 10.0.3

    2. Then add test file

      using Newtonsoft.Json;
      
    3. Usage:

      Assert.AreEqual(
          JsonConvert.SerializeObject(expected),
          JsonConvert.SerializeObject(actual));
      
    0 讨论(0)
  • 2020-11-30 03:24

    Maybe you need to add an public bool Equals(object o) to the class.

    0 讨论(0)
  • 2020-11-30 03:24
    obj1.ToString().Equals(obj2.ToString())
    
    0 讨论(0)
  • 2020-11-30 03:25

    Have a look at the following link. Its a solution on code project and I have used it too. It works fine for comparing the objects in both NUnit and MSUnit

    http://www.codeproject.com/Articles/22709/Testing-Equality-of-Two-Objects?msg=5189539#xx5189539xx

    0 讨论(0)
  • 2020-11-30 03:27

    You should provide an override of Object.Equals and Object.GetHashCode:

    public override bool Equals(object obj) {
        Student other = obj as Student;
        if(other == null) {
            return false;
        }
        return (this.Name == other.Name) && (this.ID == other.ID);
    }
    
    public override int GetHashCode() {
        return 33 * Name.GetHashCode() + ID.GetHashCode();
    }
    

    As for checking if two collections are equal, use Enumerable.SequenceEqual:

    // first and second are IEnumerable<T>
    Assert.IsTrue(first.SequenceEqual(second)); 
    

    Note that you might need to use the overload that accepts an IEqualityComparer<T>.

    0 讨论(0)
  • 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<ClassType>
    {
        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)

    0 讨论(0)
提交回复
热议问题