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



我有一个通用的测试方法,我想测试所有不合格,如果出现:

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);
        }
    }
}

好消息!您应该发现 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/开始的帖子中还有更多血腥的细节

最新更新