Integration Test with Ninject

I am familiar with the fact that I should not use dependency injection in unit tests, so I can unit test each level independently.

However, I want to create integration tests for my controllers. So I need to inject my repositories into the controllers from unit test.

I have the following general approach using a T4 script that creates a test class for each controller containing a test method for each ActionResult. This test method should simply call the method to make sure that no exceptions are thrown to the surface.

Due to using this T4 script, I cannot manually load repositories into controllers. I need to use dependency injection.

Based on my past experience, this should work, but I keep getting the error:

Unable to get default constructor for class <<UnitTest>>

My created classes look like this:

[TestClass]
public class TestControllersHomeController
{
    private EL.NET.Web.Controllers.HomeController c;
    //setup
    public TestControllersHomeController(Project.Controllers.HomeController c)
    {
        this.c = c;
    }
    [ClassInitialize]
    public void ClassInitialize()
    {

        var kernel = NinjectWebCommon.CreatePublicKernel();
        kernel.Bind<TestControllersHomeController>().ToSelf();
        kernel.Bind<Project.Controllers.HomeController>().ToSelf();
    }
    [TestMethod]
    public void TestIndex()
    {
        var result = c.Index();
        Assert.IsNotNull(result);
    }

Edit:

I already found out that repositories can be loaded using the GetService () method for IKernel. But for a membership provider, this does not work. Again, I don’t want to mock the provider, I want to perform an integration test, so I know if my Controller methods can throw any exceptions.

+5
source share
1 answer

unit test should have a default constructor:

[TestClass]
public class TestControllersHomeController
{
    private HomeController _sut;

    [TestInitialize]
    public void MyTestInitialize() 
    {
        var kernel = NinjectWebCommon.CreatePublicKernel();
        _sut = kernel.Resolve<HomeController>();
    }

    [TestMethod]
    public void TestIndex()
    {
        var result = _sut.Index();
        Assert.IsNotNull(result);
    }
}
+4
source

All Articles