I’m using Ninject in my MVC 3 project and that works fine, but I was wondering whats a good way to use Ninject in my Tests project?
Heres how I’m currently doing things:
[Fact]
public void ReturnsViewResultWithDefaultViewName()
{
// Arrange
var membershipService = new MembershipService(new EFMembershipProvider());
var transactionService = new TransactionService();
var controller = new HomeController(membershipService, transactionService);
// Act
var result = controller.Index();
// Assert
var viewResult = Assert.IsType<ViewResult>(result);
Assert.Empty(viewResult.ViewName);
}
It appears that your test is using all the dependent classes that NInject would fill in when running under the MVC framework. The real benefit of IoC comes when using mocks in your unit tests.
If you use Moq, your unit test could look something like:
This gives you the ability to create conditions that can be very difficult to cause when using the normal “run-time” objects of your application. Plus, it completely isolates your class-under-test (HomeController in your sample) from other objects which will make your unit tests run faster.
See the Moq Project or google “moq” for more information. There are, of course, alternative mocking frameworks. I’m simply more familiar with Moq.