[英]Assert that my C# function throws the same exception as another function
So in the Microsoft.VisualStudio.TestTools.UnitTesting
namespace there's an assert function Assert.ThrowsException<T>(Action)
that tests if Action
throws an exception of type T
. 因此,在
Microsoft.VisualStudio.TestTools.UnitTesting
命名空间中,有一个断言函数Assert.ThrowsException<T>(Action)
,用于测试Action
引发类型T
的异常。
But <T>
means I have to know beforehand what exception will be thrown. 但是
<T>
意味着我必须事先知道将引发什么异常。
Let's say that I'm creating a method that should throw an exception similar to another method whose code is still 'fluid' (spec still changing). 假设我正在创建一个应引发异常的方法,该方法类似于代码仍为“流体”(规格仍在更改)的另一个方法。 Let's call my function
MyClass.Func
and the other function UpstreamClass.Func
. 让我们调用我的函数
MyClass.Func
和另一个函数UpstreamClass.Func
。
(Both MyClass
and UpstreamClass
inherits from ICommonInterface
, which defines public void Func(int)
) (
MyClass
和UpstreamClass
继承自ICommonInterface
,后者定义了public void Func(int)
)
Is there a way to assert that, when fed arguments that should throw exception in both functions, the thrown exceptions are the same type? 有没有一种方法可以断言,当在两个函数中都应引发异常的联合参数时,引发的异常是同一类型?
Or, in (made-up) code: 或者,使用(虚构的)代码:
// Assume -1 should generate an exception
Assert.ThrowSameException(UpstreamClass.Func(-1), MyClass.Func(-1));
You could use such a method: 您可以使用这样的方法:
public static bool AllThrowSameException(params Action[] actions)
{
Type lastExceptionType = null;
foreach (Action action in actions)
{
try
{
action();
return false;
}
catch (Exception ex)
{
if (lastExceptionType?.Equals(ex.GetType()) == false)
return false;
lastExceptionType = ex.GetType();
}
}
return true;
}
The test would be: 测试将是:
Assert.IsTrue(AllThrowSameException(() => UpstreamClass.Func(-1), () => MyClass.Func(-1)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.