ASP.NET Core MVC Interview Question #152

What should be tested in an MVC controller unit test?

Testing, AJAX/JavaScript Integration, Localization & Advanced MVC Senior Advanced

Quick Interview Answer

Test observable controller behavior rather than framework implementation details. Typical assertions include the returned result type, selected view, ViewModel, redirect target, status result, and whether an application service was called with the expected input.

Detailed Explanation

Test observable controller behavior rather than framework implementation details. Typical assertions include the returned result type, selected view, ViewModel, redirect target, status result, and whether an application service was called with the expected input.

Avoid tests that merely reproduce MVC framework behavior. If the important behavior depends on routing, filters, model binding, middleware, authentication, or Razor rendering, an integration test is usually more appropriate.

Code Example

var result = await controller.Create(model, token);

var redirect = Assert.IsType<RedirectToActionResult>(result);
Assert.Equal("Index", redirect.ActionName);

service.Verify(
    x => x.CreateAsync(model, token),
    Times.Once);