MSTest使用不同的运行时参数重复单元测试

时间:2018-03-21 13:40:52

标签: c# .net-core mstest

我有一个通用的测试方法,如果INotification:

我想测试所有的实现
private async Task TestNotification(INotification notification)
{
   var result await _notificationService.SendNotification(notification);
   Assert.Something(result);
}

是否可以注释TestNotification方法,以便Visual Studio发现每个通知实例的测试?我目前只进行一次测试:

[TestMethod]
public async Task TestAllNotification()
{
    var notificationTypes = typeof(INotification).Assembly.GetTypes()
        .Where(t => typeof(INotification).IsAssignableFrom(t) && !t.IsAbstract)
        .ToArray();

    foreach (var type in notificationTypes)
    {
        try
        {
            var instance = (INotification)Activator.CreateInstance(type);
            await TestNotification(instance);
        }
        catch(Exception ex)
        {
            throw new AssertFailedException(type.FullName, ex);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

好消息!你会发现MsTestV2中的new-ish [DynamicData]属性可以解决你的问题:

[DynamicData(nameof(AllNotificationTypes))]
[DataTestMethod]
public async Task TestNotification(Type type)
{

}

public static Type[] AllNotificationTypes 
    => typeof(INotification).Assembly.GetTypes()
        .Where(t => typeof(INotification).IsAssignableFrom(t) && !t.IsAbstract)
        .ToArray();

https://dev.to/frannsoft/mstest-v2---new-old-kid-on-the-block是对新功能的简要介绍,但在https://blogs.msdn.microsoft.com/devops/2017/07/18/extending-mstest-v2/

开始的帖子中有更多详细信息