C# MSTest使用不同的运行时参数重复单元测试
我有一个通用的测试方法,我想测试所有的执行,如果INotification:C# MSTest使用不同的运行时参数重复单元测试,c#,.net-core,mstest,C#,.net Core,Mstest,我有一个通用的测试方法,我想测试所有的执行,如果INotification: private async Task TestNotification(INotification notification) { var result await _notificationService.SendNotification(notification); Assert.Something(result); } 是否可以注释TestNotification方法,以便VisualStudio为
private async Task TestNotification(INotification notification)
{
var result await _notificationService.SendNotification(notification);
Assert.Something(result);
}
是否可以注释TestNotification
方法,以便VisualStudio为每个通知实例发现测试?我目前只有一个测试:
[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中的新ish
[dynamicata]
属性可以解决您的问题:
[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();
这是对新特性的一个很好的简要介绍,但是从开始的帖子中有更多血淋淋的细节,我不得不通过
Select(type=>newobject[]{type})将AllNotificationTypes的返回类型更改为IEnumerable