问题描述
[Test]
public void Invalid_ID_throws_an_exception()
{
var zero = 0;
var negativeNumber = -9;
Assert.Throws<ArgumentOutOfRangeException>(() => edsp.PersonInfoById(zero));
Assert.Throws<ArgumentOutOfRangeException>(() => edsp.PersonInfoById(negativeNumber));
}
和测试方法:
public IEnumerable<PersonInfo> PersonInfoById(int id)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id),"ID must be greater than zero");
yield return new PersonInfo();
}
...但测试在第一个断言时失败,因为结果是 null
,而不是预期的 ArgumentOutOfRangeException
:
Message:
Expected: <System.ArgumentOutOfRangeException>
But was: null
我在这里做错了什么?
编辑:此外,由于某种原因,我的调试器没有进入我的测试方法 edsp.PersonInfoById
- 尽管在调试时点击了“进入”,但还是直接跳过了它。
解决方法
如果您通过对结果调用 .ToList()
强制枚举,则测试通过。
例如:
[Test]
public void Invalid_ID_throws_an_exception()
{
var zero = 0;
var negativeNumber = -9;
Assert.Throws<ArgumentOutOfRangeException>(() => edsp.PersonInfoById(zero).ToList());
Assert.Throws<ArgumentOutOfRangeException>(() => edsp.PersonInfoById(negativeNumber).ToList());
}