p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/)
-   BOOK: Professional Test Driven Development with C#: Developing Real World Applications with TDD (http://p2p.wrox.com/book-professional-test-driven-development-c-developing-real-world-applications-tdd-638/)
-   -   How to mock a dependency injection in a dependent class (http://p2p.wrox.com/book-professional-test-driven-development-c-developing-real-world-applications-tdd/94846-how-mock-dependency-injection-dependent-class.html)

smithy August 18th, 2015 02:17 PM

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?


All times are GMT -4. The time now is 10:47 AM.

Powered by vBulletin®
Copyright ©2000 - 2018, Jelsoft Enterprises Ltd.
2013 John Wiley & Sons, Inc.