3
votes

I'm new on using ninject and Dependency Injection, and have a problem using it.

I try to using Ninject on my class libray, and building an integration tests. now, I see in many example that, for using ninject is just specified the DI Module like this:

Public Class DIModule : NinjectModule
public override void Load()
{
        Bind<IUSAServices>().To<USAServices>();
} 

And then on my test class, I try to call my dependency is like this:

[TestClass]
public class USAIntegrationTests
{

    private readonly IUSAServices _usaService;

    public USAIntegrationTests(IUSAServices usaServices)
    {
        _usaService = usaServices;
    }

    [TestMethod]
    public void ValidateUserTests()
    {
        Assert.IsTrue(_usaService.ValidateUser("username1", "password1"));
    }
}

And Getting this error:

Unable to get default constructor for class USATests.IntegrationTests.USAIntegrationTests.

However I read the documentation and tried like this:

[TestClass]
public class USAIntegrationTests
{

    private readonly IUSAServices _usaService;

    public USAIntegrationTests()
    {
        using (IKernel kernel = new StandardKernel(new DIModule()))
        {
            _usaService = kernel.Get<IUSAServices>();
        }
    }

    [TestMethod]
    public void ValidateUserTests()
    {
        Assert.IsTrue(_usaService.ValidateUser("mantab", "banget"));
    }
}

The test is works properly. My question is, why I getting that error? is that some way to get around it? Thanks in advance.

2

2 Answers

5
votes

Unit test frameworks require your test classes to have a default constructor. You usually can't integrate DI containers with them. Instead of using constructor injection, you will have to call the container directly from your code, although for unit tests you should typically not have a container at all (for integration tests however, this is okay).

0
votes

You can add a paramterless constructor for the class. It worked for me.