I've built a simple class that has a dependency manually injected into its constructor.
Here is the interface for the dependency:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IRepository | |
{ | |
string Test(); | |
} |
Implement the interface:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyRepository : IRepository | |
{ | |
public string Test() | |
{ | |
return "Test"; | |
} | |
} |
Create a class that depends on the IRepository:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyWorkFactory | |
{ | |
private IRepository _repository; | |
public MyWorkFactory(IRepository repository) | |
{ | |
_repository = repository; | |
} | |
public string TestMe() | |
{ | |
return _repository.Test(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyWorkFactory myFactory = new MyWorkFactory(new MyRepository()); | |
Console.WriteLine(myFactory.TestMe()); // This should return "Test" |
All works as intended, the output is "Test" which is how we implemented the IRepository.
But when testing we want to isolate the MyWorkFactory class without having to rely on the working implementation of the IRepository interface.
So there are a few ways of going about this. We could create a new implementation of IRepository with known outcomes for testing. Or we can mock the dependency up.
I'm using Moq in this example as it's lightweight, works well on mono and is easy to use.
So let's mock/moq up the repository, inject it into the MyWorkFactory class and see what happens:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// mock up the interface | |
var mock = new Mock<IRepository>(); | |
mock.Setup(f => f.Test()).Returns("My Mock"); | |
// Pass in the mocked repository | |
MyWorkFactory myFactoryWithMoq = new MyWorkFactory(mock.Object); | |
Console.WriteLine(myFactoryWithMoq.TestMe()); // This should return "My Mock" |