Unit test with IEnumerable return type
I've been living under a rock for some years, but finaly I had to take a look at unit testing.
I'm trying to unit test a Repository that return IEnumerable
[TestMethod()]
public void GetContactsTest()
{
string sqlStr = Settings1.Default["TestSqlString"].ToString();
ContactRepository target = new ContactRepository(sqlStr);
IEnumerable<Contact> expected = new IEnumerable<Contact>();
IEnumerable<Contact> actual;
actual = target.GetContacts();
Assert.AreEqual(exp开发者_如何学JAVAected, actual);
}
But, It's not possible to create an instance off the IEnumerable for the expected object.
Could anyone guide this noob a little :)
You can't create an instance of an interface directly, you need a class that implements that interface. An array will do nicely, so you could do
IEnumerable<Contact> expected = new Contact[] {};
However, you'll also find that Assert.AreEqual
doesn't do what you want here. It'll test whether the two objects are equal, which isn't the same as testing whether they yield the same sequence. For example, an empty array of Contact and an empty List<Contact> aren't equal as objects, but they do represent the same (empty) sequence. You can test that the sequences are equal with
Assert.IsTrue(expected.SequenceEqual(actual));
精彩评论