Lesson 57 of 93 · 6 min read · Updated

Verifying the ActionResult Contract: ViewResult, RedirectToAction and NotFound

An MVC action does not render HTML in a unit test. It returns an IActionResult object, and that object is the contract between the controller and the framework. This lesson shows how to assert that contract with xUnit and FluentAssertions: the result type, the view model, the route values and the status it maps to.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. Moq 4.21.0
  4. FluentAssertions 7.2.2 (free under Apache-2.0; version 8.x requires a commercial licence)
  5. A test project with a FrameworkReference to Microsoft.AspNetCore.App

What Belongs to the Contract

When a browser calls an action, ASP.NET Core takes the returned result and turns it into a response. A ViewResult renders a Razor view with a model. A RedirectToActionResult becomes a 302 response with a Location header. A NotFoundResult becomes a 404. The unit test stops before that step and checks the result object itself.

That object carries four things worth asserting:

  1. the result type (ViewResult, RedirectToActionResult, NotFoundResult and so on),
  2. the view model,
  3. the route values of a redirect,
  4. the status code it stands for.

The view's HTML is not part of the contract in a unit test. Razor does not run, so there is nothing to check there. If you need to check rendered markup, that is an integration test.

Result Type and View Model

The Index action loads products and maps them to view models. The test checks both the type of the result and the shape of the model.

M07.WebApp/Controllers/ProductsController.cs

/// <summary>List page -> ViewResult + model.</summary>
public async Task<IActionResult> Index(CancellationToken cancellationToken)
{
var products = await repository.ListAsync(cancellationToken);

var model = products
.Select(p => new ProductViewModel(p.Id, p.Name, p.Price, p.Stock))
.ToList();

return View(model);
}

M07.WebApp.Tests/MvcControllerTests.cs

[Fact]
public async Task Index_ReturnsViewWithProductViewModels()
{
// Arrange
var repository = RepositoryWith(
new Product(1, "Mekanik Klavye", 750m, 10),
new Product(2, "Kablosuz Mouse", 250m, 25));

var sut = new ProductsController(repository.Object);

// Act
var result = await sut.Index(CancellationToken.None);

// Assert - RESULT TYPE + MODEL
var view = result.Should().BeOfType<ViewResult>().Subject;
var model = view.Model.Should().BeAssignableTo<IReadOnlyList<ProductViewModel>>().Subject;

model.Should().HaveCount(2);
model[0].Name.Should().Be("Mekanik Klavye");
}

Two FluentAssertions details make this readable. BeOfType<ViewResult>() checks the exact runtime type, and .Subject gives you the value already cast to that type. For the model the test uses BeAssignableTo<IReadOnlyList<ProductViewModel>>() instead, because the action returns a List<T>, and the test should not care which concrete collection it is. Use BeOfType when the exact type is the promise and BeAssignableTo when only the shape is.

The Details action shows the same idea with a single model, chained with .Which:

M07.WebApp.Tests/MvcControllerTests.cs

[Fact]
public async Task Details_WhenProductExists_ReturnsViewWithModel()
{
var repository = RepositoryWith(new Product(7, "Monitör", 5_000m, 3));
var sut = new ProductsController(repository.Object);

var result = await sut.Details(7, CancellationToken.None);

var view = result.Should().BeOfType<ViewResult>().Subject;
view.Model.Should().BeOfType<ProductViewModel>()
.Which.Id.Should().Be(7);
}

Route Values Are Part of the Contract

After a successful POST, the controller follows the Post/Redirect/Get pattern: it redirects to another action instead of rendering a view. A redirect to the wrong action, or to the right action with the wrong id, sends the user to the wrong page. So the test checks both ActionName and RouteValues.

M07.WebApp.Tests/MvcControllerTests.cs

[Fact]
public async Task Create_WhenSuccessful_RedirectsToDetailsWithRouteValues()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.AddAsync("Yeni Ürün", 100m, 5, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Product(42, "Yeni Ürün", 100m, 5));

var sut = new ProductsController(repository.Object)
{
// Actions that use TempData need a provider (details in the TempData lesson).
TempData = TestContextFactory.CreateTempData(),
};

var request = new CreateProductRequest { Name = "Yeni Ürün", Price = 100m, Stock = 5 };

var result = await sut.Create(request, CancellationToken.None);

// ROUTE VALUES are part of the contract too.
var redirect = result.Should().BeOfType<RedirectToActionResult>().Subject;
redirect.ActionName.Should().Be(nameof(ProductsController.Details));
redirect.RouteValues!["id"].Should().Be(42);
}

The test uses nameof(ProductsController.Details) instead of the string "Details". If someone renames the action, the compiler flags the test, and a typo cannot slip in. The id comes from the repository mock (42), not from the request, so the test proves that the controller redirects to the product that was really created.

Empty and Pre-filled Forms

GET actions that show a form also have a contract: the right model type, empty or filled with current values.

M07.WebApp.Tests/MvcControllerTests.cs

[Fact]
public void Create_Get_ReturnsEmptyForm()
{
var sut = new ProductsController(Mock.Of<IProductRepository>());

var result = sut.Create();

result.Should().BeOfType<ViewResult>()
.Which.Model.Should().BeOfType<CreateProductRequest>();
}

[Fact]
public async Task Edit_Get_WhenProductExists_ReturnsFormFilledWithCurrentValues()
{
var repository = RepositoryWith(new Product(3, "Kulaklık", 400m, 8));
var sut = new ProductsController(repository.Object);

var result = await sut.Edit(3, CancellationToken.None);

var form = result.Should().BeOfType<ViewResult>()
.Which.Model.Should().BeOfType<UpdateProductRequest>().Subject;

form.Name.Should().Be("Kulaklık");
form.Price.Should().Be(400m);
form.Stock.Should().Be(8);
}

Mock.Of<IProductRepository>() creates a dummy. The Create GET action never touches the repository, so the test does not need any setup.

The Edit GET test checks each field of the form model. This matters because the edit form is the only place where the user sees the current values. If the mapping copied the wrong field, or left one out, the user would save stale or empty data on the next POST. Three short assertions protect against that.

NotFound: the Path People Forget

A missing resource must return NotFoundResult, not a ViewResult with a null model and not an exception. The Delete action relies on the repository's bool result to decide.

M07.WebApp/Controllers/ProductsController.cs

/// <summary>Delete -> redirect to the list on success, otherwise NotFound.</summary>
[HttpPost]
public async Task<IActionResult> Delete(int id, CancellationToken cancellationToken)
{
var deleted = await repository.DeleteAsync(id, cancellationToken);

if (!deleted)
{
return NotFound();
}

TempData["Success"] = "Ürün silindi.";
return RedirectToAction(nameof(Index));
}

M07.WebApp.Tests/MvcControllerTests.cs

[Fact]
public async Task Details_WhenProductIsMissing_ReturnsNotFound()
{
// The "missing resource" scenario - the path people forget most often.
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.GetAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync((Product?)null);

var sut = new ProductsController(repository.Object);

var result = await sut.Details(999, CancellationToken.None);

result.Should().BeOfType<NotFoundResult>();
}

[Fact]
public async Task Delete_WhenProductIsMissing_ReturnsNotFound()
{
var repository = new Mock<IProductRepository>();
repository
.Setup(x => x.DeleteAsync(It.IsAny<int>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(false);

var sut = new ProductsController(repository.Object)
{
TempData = TestContextFactory.CreateTempData(),
};

var result = await sut.Delete(5, CancellationToken.None);

result.Should().BeOfType<NotFoundResult>();
}

A common mistake is to be too loose here. NotFound() returns NotFoundResult, while NotFound(value) returns NotFoundObjectResult. Both mean 404, but they are different types. BeOfType<NotFoundResult>() fails if the action starts sending a body. That is usually what you want: a change in the response shape should be a decision, not an accident.

Summary

  1. In a unit test, the IActionResult object is the contract. Razor does not run, so assert the result, not the HTML.
  2. Check the result type, the view model, the route values of a redirect and the status it maps to.
  3. Use .Subject and .Which to continue asserting on the cast value without manual casts.
  4. Prefer nameof(...) over string action names in redirect assertions.
  5. Cover the NotFound path for every action that takes an id.