Unit Tests for Main and Other Methods in Top-Level Statements Console Applications
Download full source code.
It took me a while to get used to top-level statements, and a while more to like them. Once I did, I wanted to run unit tests on the Main method, and any other methods I might add to the Program.cs file. But, because there is no explicit Main method, it is not as easy as you might first think.
The Program class
The Program class needs to be made public before you can access it from a unit test in another project. Do this by adding a public partial class Program { }
to the end of the file.
return int.Parse(args[0]) + int.Parse(args[1]); // "Main" method
int MultiplyTwoNumbers(int a, int b) // static method
{
return a * b;
}
public partial class Program { } // make the Program public
I also added a static method, MultiplyTwoNumbers
, to show how to test that.
The Unit Test Project
Create a new unit test project, and add a reference to the project that contains the Program class.
I like xUnit, so I will use that.
Here is my test for the Main method -
[Fact]
public void MainTest()
{
// Arrange
TypeInfo program = typeof(Program).GetTypeInfo();
var mainMethod = program.DeclaredMethods.Single(m => m.Name =="<Main>$"); // this finds the Main method
// Act
int result = (int) mainMethod.Invoke(null, new object[] { new string[2] {"3", "4"} });
// Assert
Assert.Equal(7, result);
}
That’s it for the Main method, a few lines but it took a bit of time to figure out.
Below is the test for the MultiplyTwoNumbers method. It is very similar to the Main method test.
[Fact]
public void MultiplyTwoNumbersTest()
{
// Arrange
TypeInfo program = typeof(Program).GetTypeInfo();
var multiplyToNumbersMethod = program.DeclaredMethods.Single(m => m.Name.Contains("MultiplyTwoNumbers"));;
// Act
int result = (int) multiplyToNumbersMethod.Invoke(null, new object[] {3, 4});
// Assert
Assert.Equal(12, result);
}
Download full source code.