Mocking objects is a very important aspect of unit testing. As you may be aware, unit testing is about testing one module at a time; any external dependency is assumed to be working fine.
There are many mocking frameworks available for .NET, including the following:
- NSubstitute (not supported in .NET core)
- Rhino Mocks (not supported in .NET core)
- Moq (supported in .NET core)
- NMock3 (not supported in .NET core)
For the sake of demonstration, we will be using Moq to mock our serviced components.
In this section, we will create a simple service containing asynchronous methods. Then, we will try to write unit test cases for the methods that call the service. Let's consider a service interface:
public interface IService
{
Task<string> GetDataAsync();
}
As we can see, the interface has a GetDataAsync() method, which fetches data...