MSTest: How to assert 2 collections
I am trying to make a unit test to see if the objects in 1 collection (and the order for that matter) are the same (as in different objects, same values) as the ones in another collection.
This fails, as apparently CollectionAssert.AreEqual is a reference test.
This fails, as apparently CollectionAssert.AreEqual is a reference test.
[TestClass()]
public class TrophiesRepositoryTests
{
private TrophiesRepository trophyRepo = new();
[TestInitialize]
public void Setup()
{
trophyRepo.Add(new Trophy { Id = 1, Competition = "World Cup", Year = 1998 });
trophyRepo.Add(new Trophy { Id = 2, Competition = "Champions League", Year = 2020 });
trophyRepo.Add(new Trophy { Id = 3, Competition = "Copa America", Year = 2016 });
trophyRepo.Add(new Trophy { Id = 4, Competition = "Euro Cup", Year = 2004 });
trophyRepo.Add(new Trophy { Id = 5, Competition = "Olympics", Year = 2008 });
}
// MethodName_StateUnderTest_ExpectedBehavior
#region Get Tests
[TestMethod()]
public void Get_WithNoParameters_ReturnsEntireList()
{
// Arrange
List<Trophy> expected = new List<Trophy>
{
new Trophy { Id = 1, Competition = "World Cup", Year = 1998 },
new Trophy { Id = 2, Competition = "Champions League", Year = 2020 },
new Trophy { Id = 3, Competition = "Copa America", Year = 2016 },
new Trophy { Id = 4, Competition = "Euro Cup", Year = 2004 },
new Trophy { Id = 5, Competition = "Olympics", Year = 2008 }
};
// Act
List<Trophy> actual = trophyRepo.Get();
// Assert
CollectionAssert.AreEqual(expected, actual);
Assert.AreEqual(5, actual.Count);
}
#endregion
}[TestClass()]
public class TrophiesRepositoryTests
{
private TrophiesRepository trophyRepo = new();
[TestInitialize]
public void Setup()
{
trophyRepo.Add(new Trophy { Id = 1, Competition = "World Cup", Year = 1998 });
trophyRepo.Add(new Trophy { Id = 2, Competition = "Champions League", Year = 2020 });
trophyRepo.Add(new Trophy { Id = 3, Competition = "Copa America", Year = 2016 });
trophyRepo.Add(new Trophy { Id = 4, Competition = "Euro Cup", Year = 2004 });
trophyRepo.Add(new Trophy { Id = 5, Competition = "Olympics", Year = 2008 });
}
// MethodName_StateUnderTest_ExpectedBehavior
#region Get Tests
[TestMethod()]
public void Get_WithNoParameters_ReturnsEntireList()
{
// Arrange
List<Trophy> expected = new List<Trophy>
{
new Trophy { Id = 1, Competition = "World Cup", Year = 1998 },
new Trophy { Id = 2, Competition = "Champions League", Year = 2020 },
new Trophy { Id = 3, Competition = "Copa America", Year = 2016 },
new Trophy { Id = 4, Competition = "Euro Cup", Year = 2004 },
new Trophy { Id = 5, Competition = "Olympics", Year = 2008 }
};
// Act
List<Trophy> actual = trophyRepo.Get();
// Assert
CollectionAssert.AreEqual(expected, actual);
Assert.AreEqual(5, actual.Count);
}
#endregion
}