Unit test ASP.NET Core Applications with MSTest

Posted by Anuraj on Tuesday, June 7, 2016

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": [
			"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.

public class EmployeeControllerTests
	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;

		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 :)

Similar Posts

Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon


Copyright © 2017 - Anuraj P. 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. Hosted with ❤ by GitHub