如何将类型传递到测试方法

本文关键字:测试方法 类型 | 更新日期: 2023-09-27 18:04:42

如何将类型传递到单元测试中?

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
}

如何将类型传递到测试方法

实现这一点的一种方法是利用推断泛型…

您将在您的测试fixture中拥有一个测试用例源。

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
    }

然后代码将从测试用例源中的异常实例推断类型。如果不实例化异常,我想不出一种方法来做到这一点……

你还没说你尝试了什么没用的。从表面上看,这似乎很容易,但也许我不明白你想做什么。

您显示的示例单元测试是不正确的。它接受一个Exception作为参数,但是你给它一个Type。根据您的标题,测试方法应该接受类型。然后像这样做…

[TestCase(typeof(SomeException))]
[TestCase(typeof(SomeOtherException))]
public void UnitTest(Type exceptionType)
{
    Assert.That(()=>_businessService.Setup(x=>x.DoWork),
        Throws.InstanceOf(exceptionType));
}

' ' '

我理解错问题了吗?