Testing Controller Action Methods

Learn to test controller action methods in .NET using xUnit testing.

We are going to create tests for some question controller actions.

Our API controller has dependencies for a cache and a data repository. We don't want our tests to execute the real cache and data repository because we require the data in the cache and data repository to be predicable. This helps us get predicable results that we can check. In addition, if the tests are running on the real database, the test execution will be much slower. So, we are going to use a library called Moq to help us replace the real cache and data repository with fake implementations that give predicable results.

Let's get started:

  1. First, we need to reference the “QandA” project from the BackendTests project. We can do this by right-clicking on the “Dependencies” node in “Solution Explorer” in the BackendTests project and choosing “Add Project Reference...”:

Get hands-on with 1200+ tech skills courses.