简体   繁体   English

无法获得单元测试项目中类的默认构造函数

[英]Unable to get Default Constructor for class in Unit Test Project

I have created a unit test project. 我已经创建了一个单元测试项目。 I get an exception specifying 我得到一个异常指定

Unable to get default constructor for class *****.Tests.Controllers.PersonRegistration 无法获取类*****。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 = "test123@gmail.com";
        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 但是我正在获得_userManager_loggingService NULL

空值

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. 请提出一种无需使用Moq或任何其他模拟框架的方法来解决此问题,以帮助我。

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. ILoggingService和IUserManager是接口。 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" 如果不确定..右键单击接口名称,然后选择“转到实现”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM