Unable to get Default Constructor for class in Unit Test Project

Harsha W picture Harsha W · Jun 2, 2017 · Viewed 10.3k times · Source

I have created a unit test project. I get an exception specifying

Unable to get default constructor for class *****.Tests.Controllers.PersonRegistration

namespace *****.Tests.Controllers
{
[TestClass]
public class PersonRegistration
  {
    private ILoggingService _loggingService;
    private IUserManager _userManager;
    public PersonRegistration(IUserManager userManager, ILoggingService loggingService)
    {
        this._userManager = userManager;
        this._loggingService = loggingService;
    }

    [TestMethod]
    public void TestMethod1()
    {
        RegisterBindingModel model = new RegisterBindingModel();
        AccountController ac = new AccountController(_userManager, _loggingService);
        model.UserName = "[email protected]";
        var result = ac.Register(model);
        Assert.AreEqual("User Registered Successfully", result);
    }
  }
}

To eradicate this issue some threads said to add an default constructor without parameters. So I added this also

public PersonRegistration()
 {
 }

But then I resolved the exception. But I am getting NULL values for _userManager and _loggingService

Null Values

How to resolve that issue. I do not want to generate null values when passing.

Please help me by suggesting a method to solve this question without using Moq or any other mocking frameworks.

Answer

Wheels73 picture Wheels73 · Jun 2, 2017

As discussed.

Runs once when the test class is initialized.

[ClassInitialize]
public void SetUp()
{
    _loggingService = new LoggingService();
    _userManager = new UserManager();
}

You can also use

 [TestInitialize]
 public void Initalize()
 {
      _loggingService = new LoggingService();
       _userManager = new UserManager();
 }

This will run before each test is ran in case you need different conditions for each test.

As discussed. ILoggingService and IUserManager are interfaces. You need to instance them to whatever implementation class "implements" that interface.

If you are unsure.. right click on the interface name and choose "Go To Implementation"