C# 单元测试中的双向列表比较
在我的 C# 单元测试中,我经常根据 ID 列表查询行列表。然后,我想确保 1) 对于所有 ID,至少找到一行具有该 ID,2) 对于所有返回的行,每一行都有一个位于要查找的 ID 列表中的 ID。我通常是这样确保的:
Assert.IsTrue(ids.All(
id => results.Any(result => result[primaryKey].Equals(id))
), "Not all IDs were found in returned results");
Assert.IsTrue(results.All(
result => ids.Any(id => result[primaryKey].Equals(id))
), "Returned results had unexpected IDs");
我认为使用 Any
和 All
进行此类检查很方便,但我想看看是否有人认为这比它的可读性差可能是,或者是否有更好的方法来进行这样的双向检查。我在 Visual Studio 2008 Team System 中使用 MSTest 进行单元测试。如果它太主观的话,这也许应该是社区维基。
编辑:我现在正在使用基于 Aviad P. 的建议的解决方案,以及以下测试通过的事实:
string[] ids1 = { "a", "b", "c" };
string[] ids2 = { "b", "c", "d", "e" };
string[] ids3 = { "c", "a", "b" };
Assert.AreEqual(
1,
ids1.Except(ids2).Count()
);
Assert.AreEqual(
2,
ids2.Except(ids1).Count()
);
Assert.AreEqual(
0,
ids1.Except(ids3).Count()
);
In my C# unit tests, I often query for a list of rows based on a list of IDs. I then want to ensure that 1) for all the IDs, there was at least one row found that has that ID and 2) for all the returned rows, each row has an ID that is in the list of IDs to find. Here is how I usually ensure that:
Assert.IsTrue(ids.All(
id => results.Any(result => result[primaryKey].Equals(id))
), "Not all IDs were found in returned results");
Assert.IsTrue(results.All(
result => ids.Any(id => result[primaryKey].Equals(id))
), "Returned results had unexpected IDs");
I think the use of Any
and All
is convenient for such checks, but I wanted to see if anyone thinks this is less readable than it could be, or if there is perhaps a nicer way of doing two-way checks like this. I'm using MSTest in Visual Studio 2008 Team System for unit testing. This perhaps should be community wiki if it's too subjective.
Edit: I'm now using a solution based on Aviad P.'s suggestion, and also the fact that the following test passes:
string[] ids1 = { "a", "b", "c" };
string[] ids2 = { "b", "c", "d", "e" };
string[] ids3 = { "c", "a", "b" };
Assert.AreEqual(
1,
ids1.Except(ids2).Count()
);
Assert.AreEqual(
2,
ids2.Except(ids1).Count()
);
Assert.AreEqual(
0,
ids1.Except(ids3).Count()
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以选择使用
Except
运算符:You might choose to use the
Except
operator:IMO,可读性不高。创建并记录一个返回 true / false 的方法。然后调用 Assert.IsTrue(methodWithDescriptiveNameWhichReturnsTrueOrfalse(), "失败原因");
IMO, not as readable as it could be. Create and document a method which returns true / false. Then call Assert.IsTrue(methodWithDescriptiveNameWhichReturnsTrueOrfalse(), "reason for failure");
这是我用来处理两个枚举的代码片段,并在进行单元测试时抛出异常在 MS Test 中,它可能会有所帮助:
使用
比较两个枚举:
管理异常
代码
Here is a snippet of code I made to deal with two enumerables, and throwing exception while doing Unit test In MS Test, it might help :
Use
compare two enumerables:
manage exception
Code
NUnit 具有
CollectionAssert
系列断言,有助于提高可读性。NUnit has the
CollectionAssert
family of assertions which help readability.