开发者

xUnit.net with Ninject

开发者 https://www.devze.com 2023-02-12 07:22 出处:网络
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?

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 re开发者_高级运维sult = 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:

    // Arrange
    var membershipService = new Mock<IMembershipService>();
    membershipService.Setup(m => m.CurrentUser)
        .Returns(new MyPrincipal() { Name = "Bob", ID = 12345 });
    var transactionService = new Mock<ITransactionService>();
    transactionService.Setup(t => t.SomeRandomMethod())
        .Throws<MyBadTransactionException>();
    var controller = new HomeController(membershipService.Object, transactionService.Object);
...

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.


The geneally accepted advice is: dont use Ninject in tests - the goal of using IoC is that you dont need heavy stuff in your tests in the first place. It'll help the code to tell you when things are getting too complex.

If you feel your code really has unavoidable complexity that you cant make satisfactory by improving the design, look at AutoFixture, esp the xunit.net integration - it and and/or other automocking containers may be suitable as they directly address the sort of concern you're hilighting in your question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号