In this article, I present an example of using Mock Objects in .NET 7, based on a project created in previous versions of .NET and detailed in an article published some time ago on my blog:
Software Testing with .NET 5: usage examples (Portuguese)
The implementation in question used Moq as an alternative for handling Mock Objects, in addition to being based on xUnit and also using the Fluent Assertions framework. I’ve even made this example available on GitHub:
https://github.com/renatogroffe/DotNet7-Moq-xUnit-FluentAssertions_AnaliseCredito
If you find this useful, please give a ⭐️ to support. I also invite you to follow me on GitHub!
Starting from the IServicoConsultaCredito interface:
And the StatusConsultaCredito enum and the Pendencia class, constructions used by the IServicoConsultaCredito interface: I’ve even made this example available on GitHub:
We will have the use these structures in the AnaliseCredito class:
And how could we then generate an object through the IServicoConsultaCredito interface without having an implementation of it?
The answer lies in the generic class Mock (namespace Moq), made available by Moq for creating Mock Objects. The following listing exemplifies all this, with the configuration of mappings in the constructor of type TestesAnaliseCredito and the use of a Mock Object simulating the possible conditions to be treated by AnaliseCredito:
This example was presented in detail in a recent live on Microsoft Reactor, with the content being able to watch for free on YouTube (in Portuguese):
References
MOQ | The most popular and friendly mocking framework for .NET
.NET + xUnit: Categorizing and Organizing Tests with Traits
*O conteúdo deste artigo é de responsabilidade do(a) autor(a) e não reflete necessariamente a opinião do iMasters.
Leave a comment