Moq在点网核心中进行依赖注入的单元测试中的设置方法是什么

时间:2018-07-30 08:20:35

标签: c# unit-testing dependency-injection .net-core moq

我有dot net core网站,基于依赖注入,控制器是。

public class TokenController : Controller
{
    private IConfiguration _config;
    private readonly IUserService _iuserService;

    public TokenController(IConfiguration config, IUserService iUserService)
    {
        _config = config;
        _iuserService = iUserService;
    }
     public UserViewModel Authenticate(LoginModel login)
    {
        UserViewModel user = null;
        user = this._iuserService.Login(login.Username, login.Password);
        return user;
    }

  }

我想对Authenticate方法进行单元测试,单元测试类是

 [TestClass]
 public class TokenUnitTest
 {
    private IUserService _IUserService;
    private IConfiguration _config;

    [TestInitialize]
    public void Setup()
    {
        var mockIUserService = new Mock<IUserService>();
        UserViewModel returnedobj = new UserViewModel();
        returnedobj.Email = "sam@sam.com";
        returnedobj.Name = "sam";
        mockIUserService.Setup(x => x.Login("sam", "123")).Returns(returnedobj);
        _IUserService = mockIUserService.Object;

        var _configurationRoot = new Mock<IConfigurationRoot>();
        _configurationRoot.SetupGet(x => x[It.IsAny<string>()]).Returns("Key");
        this._config = _configurationRoot.Object;
    }
  [TestMethod]
    public void Authenticate()
    {
        ////arrange

        LoginModel _LoginModel = new LoginModel("sam", "123");
        var config = InitConfiguration();
        var clientId = config["CLIENT_ID"];
        TokenController _TokenController = new TokenController(config, _IUserService);
        ////act
        UserViewModel LoginnedUser = _TokenController.Authenticate(_LoginModel);

        ////assert
        Assert.IsNotNull(LoginnedUser);
    }
}

问题是,当我将断点放在authenticate方法上时,它返回setupMock中存在的返回数据。为什么它不进入数据库并返回真实数据。 第二个问题是断点没有输入UserService,它处理接口,为什么依赖项注入不起作用?

1 个答案:

答案 0 :(得分:0)

对于集成测试,无需模拟:

[TestInitialize]
public void Setup()
{
    _IUserService = new UserService(); // create a real instance
}