.NET: Mocking and unit testing strategy pattern resolver method in dependency injection context.

Javier Carracedo
.Net Programming
Published in
1 min readApr 29, 2023

Hi! 😁

In the last days, I was working in a problem like the suggested in the title. With .NET, I was coding a strategy pattern to solve a challenge. My problem was that, I wanted testing a source code similar that the described next 🤔

Moq and NUnit framework help me to implement a couple of unit tests 🧐. The source code that I had to test it was very similar that this:

What was the challenge to use Moq framework? I had to mocking some class of the .NET framework. Due to the extensions method, like this, need replicate the behavior to mocking it 👇

As you can see, I am doing a unit test method with different tests cases to testing GetPaymentStrategy method. This method it´s a extension method, thats extend the funcionality of ServiceProvider provider class when it´s called in a example 👌.

Finally, you can see a simple program example using GetPaymentStrategy method 😎:

And here it is the corresponding program console output 👨‍🏫:

If you want see the source code used on this example, you can see in the following link Github link 👨‍💻:

Bye! 😄✌️

--

--

Javier Carracedo
.Net Programming

Hi! SW Engineer from León (Spain) . I ❤ my work, I like improve and to grow my knowledge about different technologies. SW Engineer at HP SCDS - León (Spain)