Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 layer independently.

Still, I want to create integration tests for my controllers. Therefore I need to inject my repositories into the Controllers from a unit test.

I a following a generic 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 no exceptions are thrown to the surface.

Because of using this T4 script, I cannot manually feed the repositories into the controllers. I need to make use of dependency injection.

Based on my former experience, this should work, but i keep getting the error:

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

My generated classes look like this at the moment:

[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 the repositories can be loaded with help of the GetService() method of IKernel. But for the Membership provider, this doesn't work. Again, I do not want to mock the provider, I want to perform an integration test so I know if my Controller methods throw any exceptions.

like image 282
ckonig Avatar asked Oct 08 '22 17:10

ckonig


1 Answers

The unit test must 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);
    }
}
like image 172
Darin Dimitrov Avatar answered Oct 12 '22 10:10

Darin Dimitrov