Last active
October 21, 2018 16:05
-
-
Save secretorange/a1b477e57dc87a7ea9617b46b6619738 to your computer and use it in GitHub Desktop.
Version attribute for MSTest, useful for testing versioned API endpoints.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]})"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After debugging all tests, the output is: