[英]NUnit 3: no exception of the exact type was thrown?
How can I assert that no exception of the exact type was thrown in my code? 如何断言我的代码中没有抛出确切类型的异常?
Both 都
Assert.That(testDelegate, Throws.Nothing); // any type of an exception was not thrown
and 和
Assert.That(testDelegate, Throws.InstanceOf<ExactException>()); // an exception of needed type was thrown
are not correct way here 这里不是正确的方法
It sounds like you want 听起来像你想要的
Assert.That(testDelegate, Throws.TypeOf<ExactException>());
InstanceOf
means "of the exact type or a derived type" - just like how is
works. InstanceOf
的意思是“确切类型或派生类型” -随便怎么样is
作品。 We use TypeOf
to mean it must be the exact type. 我们使用
TypeOf
表示它必须是确切的类型。 It creates an ExactTypeConstraint
. 它创建一个
ExactTypeConstraint
。
OTOH, if you want to make a negative test (that it does not throw ExactException
) then you can't use the fluent syntax. OTOH,如果要进行否定测试( 不抛出
ExactException
),则不能使用流利的语法。 You could specify the constraint expression directly, like this... 您可以像这样直接指定约束表达式。
Assert.That(testDelegate,
new NotConstraint(
new ThrowsConstraint(
new ExactTypeConstraint(typeof(ExactException)))));
I'm not recommending that, but it's available. 我不建议这样做,但是可以使用。 I'd use Rob's workaround if I had to do this, but I'd also question why I was doing it and hopefully find a way to avoid a situation where any exception except a certain one is OK.
如果必须这样做,我会使用Rob的解决方法,但是我也想问我为什么要这样做,并希望找到一种方法来避免出现除某个例外以外的任何例外都可以的情况。
NUnit does not have a constraint that says something like Does.Not.Throw.TypeOf<ExactException>()
and passes for/ignores other exceptions. NUnit没有说类似
Does.Not.Throw.TypeOf<ExactException>()
类的约束,并且传递/忽略其他异常。 It is a fairly rare use case to test that a method does not throw a specific exception, but pass if any other exception is thrown. 测试一种方法不会引发特定的异常,而是在引发任何其他异常的情况下通过的情况是很少见的用例。 To me, it is a code smell , but if you really want to do it, you can get the behavior you want like this,
对我来说,这是一种代码味道 ,但如果您确实想这样做,则可以得到想要的行为,
[Test]
public void DoesNotThrowSpecificException()
{
try
{
MethodThatShouldntThrowExactException(); // But may throw any other exception
}
catch (Exception ex)
{
Assert.That(ex, Is.Not.TypeOf(typeof(ExactException)));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.