Skip to main content

Posts

Showing posts with the label NSubstitute

NSubstitute–Checking received calls

Although I prefer stubbing over mocking as much as possible, sometimes it is unavoidable to check the behavior of your test objects. It is a tradeoff to make between rewriting the application logic to make it easier testable or using some mocking magic. In NSubstitute, the stubbing library of my choice, you can use the Received() or DidNotReceive() extension methods: More information: https://nsubstitute.github.io/help/received-calls/

Mocking the HttpClient with NSubstitute

While reviewing some code I noticed that a project was using both Moq and NSubstitute. It seemed strange to me to use 2 mocking libraries in the same codebase. Turned out that there was a problem when trying to combine IHttpClientFactory and NSubstitute. The reason is that the IHttpClientFactory returns a concrete type (HttpClient) and that NSubstitute cannot mock its methods (like SendAsync()). The trick was to create your own HttpMessageHandler instead: The mocking code became the following: