Skip to content

Instantly share code, notes, and snippets.

@secretorange
Last active October 21, 2018 16:05
Show Gist options
  • Save secretorange/a1b477e57dc87a7ea9617b46b6619738 to your computer and use it in GitHub Desktop.
Save secretorange/a1b477e57dc87a7ea9617b46b6619738 to your computer and use it in GitHub Desktop.
Version attribute for MSTest, useful for testing versioned API endpoints.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
namespace UnitTestProject
{
[TestClass]
public class UnitTests
{
[TestMethod]
[Version(from: 1, to: 2)]
public void VersionsOneAndTwo(int version)
{
// Hit versioned endpoints...
Debug.WriteLine($"VersionsOneAndTwo: v{version}");
}
[TestMethod]
[Version(from: 1)]
public void AllVersions(int version)
{
// Hit versioned endpoint...
Debug.WriteLine($"AllVersions: v{version}");
}
[TestMethod]
[Version(from: 1, to: 1)]
public void VersionOneOnly(int version)
{
// Hit versioned endpoints...
Debug.WriteLine($"VersionOneOnly: v{version}");
}
}
}
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace UnitTestProject
{
public static class Config
{
public const int LatestVersion = 3;
}
public class VersionAttribute : Attribute, ITestDataSource
{
private readonly int From;
private readonly int To;
public VersionAttribute(int from)
: this(from, Config.LatestVersion)
{
}
public VersionAttribute(int from, int to)
{
if (from < 1)
throw new ArgumentException("from must be greater than zero", "from");
if (to < from)
throw new ArgumentException("to must be greater than or equal to zero", "to");
if (to > Config.LatestVersion)
throw new ArgumentException("to can't be greater than the latest version", "to");
From = from;
To = to;
}
public IEnumerable<object[]> GetData(MethodInfo methodInfo)
{
return Enumerable.Range(From, To).Select(i => new object[] { i });
}
public string GetDisplayName(MethodInfo methodInfo, object[] data)
{
return $"{methodInfo.Name} (v{data[0]})";
}
}
}
@secretorange
Copy link
Author

secretorange commented Oct 21, 2018

After debugging all tests, the output is:

VersionsOneAndTwo: v1
VersionsOneAndTwo: v2
AllVersions: v1
AllVersions: v2
AllVersions: v3
VersionOneOnly: v1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment