在 xUnit 中验证集合大小的惯用方法是什么? [英] What's the idiomatic way to verify collection size in xUnit?

查看:25
本文介绍了在 xUnit 中验证集合大小的惯用方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的测试套件中有一个类似这样的测试:

I have in my test suite a test that goes something like this:

[Fact]
public void VerifySomeStuff()
{
    var stuffCollection = GetSomeStuff();

    Assert.Equal(1, stuffCollection.Count());
}

这个测试按我的预期工作,但是当我运行它时,xUnit 会打印一个警告:

This test works as I expect, but when I run it xUnit prints a warning:

警告 xUnit2013:不要使用 Assert.Equal() 检查集合大小.

warning xUnit2013: Do not use Assert.Equal() to check for collection size.

但是,警告中没有建议替代方案,谷歌搜索将我带到 xUnit 中的源代码,以进行验证此警告是否打印的测试.

However, no alternative is suggested in the warning, and a google search takes me to the source code in xUnit for the test that verifies this warning is printed.

如果 Assert.Equal() 不是验证集合长度的正确方法,什么是?

If Assert.Equal() isn't the correct way to verify the length of a collection, what is?

澄清:我意识到我可以欺骗"xUnit使其不发出此警告,例如提取变量或使用 Assert.True(stuff.Count() == 1) 代替.后者只是 hacky,前者感觉就像 xUnit 是例如试图避免 IEnumerable 的多次迭代,那么这是错误的方法(因为如果它是一个问题,我会单独获得编译器提示),而 xUnit 本身永远不应该有多次评估输入(实际上,无论变量提取如何,它都可能获得相同的输入,因为 C# 函数调用的工作方式).

To clarify: I realize that I could "trick" xUnit into not emitting this warning by e.g. extracting a variable or using Assert.True(stuff.Count() == 1) instead. The latter is just hacky, and the former feels like if xUnit is e.g. trying to avoid multiple iterations of an IEnumerable<T>, then this is the wrong way to go (because I'll get compiler hints about that separately if it's an issue), and xUnit itself should never have to evaluate the input more than once (in fact it probably will get the same input regardless of variable extraction, because of how C# function calling works).

所以,我不只是想从我的输出中删除那个警告.我的问题的答案还解释了为什么首先将警告包含在库中,以及为什么我应该使用的任何方法都更好.

So, I'm not just interested in removing that warning from my output. An answer to my question also explains why that warning is included in the library in the first place and why whatever approach I should use instead is better.

推荐答案

Xunit 为其大部分警告提供了快速修复,因此您应该能够看到它认为什么是正确的".

Xunit offers quick fixes for most of its warnings, so you should be able to see what it thinks is "right".

就您而言,它希望您使用 Assert.Single,因为您只需要一个项目.如果你断言一个任意数字,比如 412,那么它不会给你关于使用 Count 的警告.如果您需要一个项目,它只会建议使用 Single,如果您没有任何项目,它会建议使用 Empty.

In your case, it wants you to use Assert.Single since you are expecting exactly one item. If you were asserting an arbitrary number, like 412, then it would not give you a warning about using Count. It will only suggest using Single if you are expecting one item, or Empty if you are expecting no items.

这篇关于在 xUnit 中验证集合大小的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆