MSTest 使用不同的运行时参数重复单元测试
MSTest repeat unit test with different runtime parameter
我有一个通用的测试方法,如果 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);
}
}
}
好消息!你应该会发现 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 is a good brief intro to the new features, but there are more gory details in posts starting at https://blogs.msdn.microsoft.com/devops/2017/07/18/extending-mstest-v2/
我有一个通用的测试方法,如果 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);
}
}
}
好消息!你应该会发现 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 is a good brief intro to the new features, but there are more gory details in posts starting at https://blogs.msdn.microsoft.com/devops/2017/07/18/extending-mstest-v2/