How to mock a dependency injection in a dependent class
Hi,
I'm trying to get to grips with TDD and am at the stage where I am trying to mock database access. I have closely followed Chapter 5 and have set up Ninject etc. However, in my real life application, my equivalent to the BusinessService class takes an IDialogService as a parameter. The reason for this is to stop Message Boxes displaying when running the unit tests. I therefore have the following line in the module:
Bind<IDialogService>().To<DialogService>();
The implementation of IDialogService is as follows:
public interface IDialogService
{
void ShowMessageBox(string caption);
}
public class DialogService : IDialogService
{
public void ShowMessageBox(string caption)
{
MessageBox.Show(caption);
}
}
public class DialogSupressedService : IDialogService
{
public void ShowMessageBox(string caption)
{
return;
}
}
I use DialogService in my application and DialogSupressedService in my unit test. However, when I create an instance of my equivalent to the BusinessService class using the Ninject Kernel, I can't figure out how to force it to use the DialogSupressedService in the unit test.
I hope I have explained this clearly.
Thanks in advance for any help.
Edit: I have realised one solution to this is to maintain two separate module files i.e. one for unitest containing:
Bind<IDialogService>().To<DialogSupressService>();
and one for the actual application containing:
Bind<IDialogService>().To<DialogService>();
Is this the right way to go?
Last edited by smithy; August 18th, 2015 at 03:48 PM..
Reason: Possible solution
|