Mocking and faking tests in Blazor and bUnit
Writing stable unit tests requires isolation for the unit under test as the unit tests should run frequently in different environments and on different machines. So, to keep the tests reliable, they should be written in isolation from external factors such as communicating with an API or asking for an access token.
Mocking and faking are the keys to simulating the behavior of the dependencies of the unit under test. For example, the Index page depends on IBooksService
, and the implementation we have is called BooksHttpClientService
, which sends requests to the API to fetch the books needed for the Index page. If we want to test IBooksService
, we need to mock it and write a fake implementation for the GetAllBooksAsync
method so the unit test can rely on this fake service instead of the actual API.
In order to mock services in .NET, there are many available packages, but Moq is the most common one, and it’s the one we will be...