In ProductService, let's make sure our service returns product data without failure by testing it. Here we will use fake objects to do so, follow these steps:
- Add a new folder and name it Fake in the FlixOne.BookStore.ProductService.UnitTests project.
- Under the Fake folder add the ProductData.cs class and add the following code:
public class ProductData
{
public IEnumerable<ProductViewModel> GetProducts()
{
var productVm = new List<ProductViewModel>
{
new ProductViewModel
{
CategoryId = Guid.NewGuid(),
CategoryDescription = "Category Description",
CategoryName = "Category Name",
ProductDescription = "Product Description",
ProductId = Guid.NewGuid(),
ProductImage = "Image full path",
ProductName = "Product Name",
ProductPrice = 112M
},
new ProductViewModel
{
CategoryId = Guid.NewGuid(),
CategoryDescription = "Category Description-01",
CategoryName = "Category Name-01",
ProductDescription = "Product Description-01",
ProductId = Guid.NewGuid(),
ProductImage = "Image full path",
ProductName = "Product Name-01",
ProductPrice = 12M
}
};
return productVm;
}
public IEnumerable<Product> GetProductList()
{
return new List<Product>
{
new Product
{
Category = new Category(),
CategoryId = Guid.NewGuid(),
Description = "Product Description-01",
Id = Guid.NewGuid(),
Image = "image full path",
Name = "Product Name-01",
Price = 12M
},
new Product
{
Category = new Category(),
CategoryId = Guid.NewGuid(),
Description = "Product Description-02",
Id = Guid.NewGuid(),
Image = "image full path",
Name = "Product Name-02",
Price = 125M
}
};
}
}
In the previous code snippet, we are creating fake data by creating two lists of ProductViewModel and Product.
- Add the Services folder in the FlixOne.BookStore.ProductService.UnitTests project.
- Under the Services folder add the ProductTests.cs class.
- Open NuGet Manager and then search for and add moq, refer to the following screenshot:
- Add the following code to the ProductTests.cs class:
public class ProductTests
{
[Fact]
public void Get_Returns_ActionResults()
{
// Arrange
var mockRepo = new Mock<IProductRepository>();
mockRepo.Setup(repo => repo.GetAll()).
Returns(new ProductData().GetProductList());
var controller = new ProductController(mockRepo.Object);
// Act
var result = controller.GetList();
// Assert
var viewResult = Assert.IsType<OkObjectResult>(result);
var model = Assert.IsAssignableFrom<IEnumerable<
ProductViewModel>>(viewResult.Value);
Assert.NotNull(model);
Assert.Equal(2, model.Count());
}
}
In the preceding code example, which is a unit test example, we are mocking our repository and testing the output of our WebAPI controller. This test is based on the AAA technique; it will be passed if you meet the mocked data during setup.