Skip to content

A C# source generator for quick creation of simple unit tests.

License

Notifications You must be signed in to change notification settings

sungaila/InlineTest

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

InlineTest Logo Sungaila.InlineTest

Azure DevOps builds (branch) Azure DevOps tests (branch) SonarCloud Quality Gate NuGet version NuGet downloads GitHub license

A C# source generator for quick creation of simple unit tests. Just add these attributes to your method:

  • [AreEqual]
  • [AreNotEqual]
  • [IsTrue]
  • [IsFalse]
  • [IsNull]
  • [IsNotNull]
  • [IsInstanceOfType<T>]
  • [IsNotInstanceOfType<T>]
  • [ThrowsException<T>]

Example

[AreEqual(6, 3, Expected = 2)]
[AreEqual(1, 1, Expected = 1)]
[AreNotEqual(10, 1, NotExpected = 42)]
[ThrowsException<ArgumentOutOfRangeException>(1, 0)]
public static int Divide(int dividend, int divisor)
{
	if (divisor == 0)
		throw new ArgumentOutOfRangeException(nameof(divisor));

	return dividend / divisor;
}

The source generator will produce classes containing the matching unit tests.

// shortened code for readability
[GeneratedCode("Sungaila.InlineTest", "1.0.0+17ac90a4b0b471c88edc5fcedee4124a7cbbac28")]
[TestClass]
public partial class ReadmeExampleTests
{
	[TestMethod]
	[DataRow(6, 3, 2)]
	[DataRow(1, 1, 1)]
	public void DivideAreEqual(int dividend, int divisor, int expected)
	{
		var result = ReadmeExample.Divide(dividend, divisor);
		Assert.AreEqual(expected, result);
	}

	[TestMethod]
	[DataRow(10, 1, 42)]
	public void DivideAreNotEqual(int dividend, int divisor, int notExpected)
	{
		var result = ReadmeExample.Divide(dividend, divisor);
		Assert.AreNotEqual(notExpected, result);
	}

	[TestMethod]
	[DataRow(1, 0)]
	public void DivideThrowsException_ArgumentOutOfRangeException(int dividend, int divisor)
	{
		Assert.ThrowsException<ArgumentOutOfRangeException>(
			() => ReadmeExample.Divide(dividend, divisor));
	}
}

Restrictions

  1. The method must be defined inside a class or struct.
    • These must be public or internal
    • For classes without a parameterless constructor the method must be static
  2. The method must follow the rules of a test method (MSTest).
    • must be public
    • cannot be async void
    • cannot use generics
  3. The method must not have more than 15 parameters.
  4. The same Attribute rules apply here. Your parameters have to be either
    • a constant value
    • a System.Type (defined at compile-time)
    • a single-dimensional array of the above