Moq and IoC experiments

Hello all. It’s been a while since I wrote something, why not restart with some interesting piece of code? I’ve embraced the whole TDD (Test Driven Development) movement and felt the need to use a mocking framework. What is does for you is basically mock the dependencies of the code you want to test, this way, you’re not worried about your code accessing a service or a database, you just test your code and ignore the rest, as you’re supposed to. Moq does this pretty well, imagine you have:


To test your code, you don’t need to execute the logic within GetValue, because your test subject is something else, so, you want to mock the behaviour of GetValue, so it returns a predefined value, and move on. You can do it with Moq, like this:


This creates a new mocked instance of an object implementing your interface, IMyClass, and sets the return value of its method to what we need, so in order to use it, we just use the Object property of the mocked object, which gives us something of type IMyClass:


Use case for this? imagine you have this code to get tested:


This way, you could easily test this, right? Now, to go the extra mile with this, you could even use something like AutoFixture, that provides a plugin for Moq, so you can’t use IoC to inject these mocked instances onto your test subjects classes, so easily as: