Liero
Liero

Reputation: 27360

MSTest repeat unit test with different runtime parameter

I have a universal test method and I want to test all impementation if INotification:

private async Task TestNotification(INotification notification)
{
   var result await _notificationService.SendNotification(notification);
   Assert.Something(result);
}

Is it possible to annotante the TestNotification method so that Visual Studio will discover tests for each instance of notification? I have currently only single test:

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

Upvotes: 1

Views: 2080

Answers (1)

Chris F Carroll
Chris F Carroll

Reputation: 12380

Good news! You should find that the new-ish [DynamicData] attribute in MsTestV2 can solve your case:

[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/

Upvotes: 2

Related Questions