In this recipe, you will learn how to test Web API controllers with Moq and xUnit.
Let's create a class library project with VS 2017, and use the ProductAPIController
methods created in the Using ActionResults recipe of this chapter. We will create some test cases for this API.
- First, let's create a class library project in the solution:
- Next, we will change the generated code in the project to import
xunit
,dotnet-test-xunit
, andmoq
. We will also have to add the reference on the Web API project.
- Here are some of the test methods:
public class ProductApiControllerTests { #region Tests for GET : api/productapi [Fact] public void GET _Returns404NotFoundResultIfProductListHaveNoItemsInRepo() { // Arrange var mockRepo = new Mock<IProductRepository>(); var emptyProductList = GetEmptyProductsList(); mockRepo.Setup(repo => repo.GetAllProducts()) .Returns(emptyProductList); var controller = new ProductApiController...