Unit test ASP.NET Core Applications with MSTest

June 07, 2016 by Anuraj

C# ASP.NET ASP.NET Core Unit Testing MS Test

This post is about running aspnet core unit tests with MS Test. Few days back Microsoft announced support of MS Test for ASP.NET Core RC2 applications. And MS released two nuget packages to support the development as well as tooling. Similar to XUnit, MS Test also require reference of MS Test Framework and tool to run the unit tests aka Test Runner. So in the project.json file add reference of “dotnet-test-mstest”, which the test runner and “MSTest.TestFramework” is the framework.

Here is the project.json file.

{
	"testRunner": "mstest",
	"dependencies": {
		"Microsoft.NETCore.Platforms": "1.0.1-*",
		"Microsoft.AspNetCore.Diagnostics": "1.0.0-*",
		"Microsoft.AspNetCore.Mvc": "1.0.0-*",
		"dotnet-test-mstest": "1.0.1-preview",
		"MSTest.TestFramework": "1.0.0-preview"
	},
	"frameworks": {
		"net451": {},
		"netcoreapp1.0": {
			"imports": [
				"dnxcore50",
				"portable-net451+win8"
			],
			"dependencies": {
				"Microsoft.NETCore.App": {
					"version": "1.0.0-*",
					"type": "platform"
				}
			}
		}
	}
}

I have removed all the sections in the project.json file which is not relevant to this blog post. Now you can write the test cases using MS Test attributes and execute the tests with “dotnet test” command.

Here is the simple asp.net core unit test with MS Test.

[TestClass]
public class EmployeeControllerTests
{
	[TestMethod]
	public void VerifyIndexDisplaysAllEmployees()
	{
		var employeeRepository = new Mock<IEmployeeRepository>();
		employeeRepository.Setup(x => x.FindAll()).Returns(new List<Employee>()
		{
			new Employee() { Id = 1, Name = "Employee 1" },
			new Employee() { Id = 2, Name = "Employee 2" },
			new Employee() { Id = 3, Name = "Employee 3" }
		});
		var employeeController = new EmployeeController(employeeRepository.Object);
		var indexResult = employeeController.Index() as ViewResult;

		Assert.IsNotNull(indexResult);
		var employees = indexResult.ViewData.Model as List<Employee>;
		Assert.AreEqual(3, employees.Count);
		Assert.AreEqual(1, employees[0].Id);
		Assert.AreEqual("Employee 3", employees[2].Name);
	}
}

Here is the typical output you will get while executing the tests.

MS Test Runner executing ASP.NET Core Unit Tests

Happy Programming :)

Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub