简体   繁体   English

nUnit Assert.Throws TestCase属性

[英]nUnit Assert.Throws TestCase attribute

I have a test method like this: 我有这样的测试方法:

[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
[TestCase(16441, "BobBank2.site16441.1", "16441.1")]
[TestCase(16443, "BobBank2.site16443.1", "16443.1")]
public async Task CheckUserAccountLinkStatusTest(int providerId, string username, string userKey)

I need to make sure that the first case (16486) throws an error, always. 我需要确保第一种情况(16486)始终会引发错误。 Is it possible to modify the TestCase attribute to do this? 是否可以修改TestCase属性来执行此操作?

You could check 你可以检查一下

if(providerId==16486)
{
    Assert.Throws(...
}

but it would be better to have two separate tests, one that checks for the exception when it is expected and one that asserts that there is no exception when there shouldn't be. 但是最好有两个单独的测试,一个是在预期发生时检查异常,另一个是断言不应出现异常的断言。

While the @Connel.O'Donnell solution works, I'd suggest to: 虽然@ Connel.O'Donnell解决方案有效,但我建议:

  1. Avoid conditional logic in unit tests. 在单元测试中避免条件逻辑。
  2. Separate tests that throws exception from those which doesn't throw one. 将引发异常的测试与不引发异常的测试分开。

So, your new, separated test for asserting exception should more or less look like: 因此,用于断言异常的新的分离测试应该大致类似:

[TestCase(16486, "BobBank2.site16486.1", "16486.1")]
public async Task CheckUserAccountLinkStatusTest_ThrowsException(int providerId, string username, string userKey)
{
    // ...
    Assert.That(() => { /* ... */  }, Throws.Exception);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM