如何将类型传递到单元测试中?
public void MethodUnderTest()
{
try
{
var businessService = _businessService.DoWork();
}
catch (SomeException exception)
{
//do some stuff
}
catch (SomeOtherException exception)
{
//do other stuff
}
}
My unit test should be something like this:
[TestCase(typeof(SomeException))]
[TestCase(typeof(SomeOtherException))]
public void UnitTest(Exception exception)
{
_businessService.Setup(x=>x.DoWork).Throws.InstanceOf<exception>();
//verify that when we called DoWork, that the logic inside of one of the catches was executed
}
答案 0 :(得分:0)
通过利用推断的泛型,可以实现的一种方法是
您的测试夹具中将有一个测试用例源。
public static List< Exception > Exceptions => new List< Exception >
{
new InvalidOperationException(),
new OverflowException()
};
然后将您的单元测试方法修改为:
[Test]
[TestCaseSource(nameof( Exceptions ))]
public void UnitTest<T>( T exception ) where T : Exception, new(){
_businessService.Setup(x=>x.DoWork).Throws.InstanceOf<T>();
//verify that when we called DoWork, that the logic inside of one of the catches was executed
}
然后代码将从测试用例源中的异常实例推断出类型。在实例化异常时,我想不出办法做到这一点......
答案 1 :(得分:0)
你还没有说过你尝试过的没用的东西。从表面上看,这似乎很容易,但也许我不明白你想做什么。
您显示的示例单元测试不正确。它将Exception作为参数,但是你给它一个Type。根据您的标题,测试方法应该接受一种类型。然后做一些像......
@section('content')
@include('3show.blade.php')
@endsection
```
我误解了这个问题吗?