如何使用Moq ApplicationUser,ApplicationContextdb,IEmailSender和IConfirguration编写测试用例

时间:2019-01-28 11:48:37

标签: c# unit-testing asp.net-core .net-core

需要您帮助如何在ASP.net核心身份用户中编写单元测试用例。

在当前设计中,我的控制器使用依赖项注入。它注入了所有低于类

  • ApplicationUser“用于身份验证”
  • ApplicationDbContext“用于实体框架”
  • “电子邮件发送者”用于发送邮件”
  • IConfiguration“没用目的”

我有一个具有依赖注入功能的控制器,该控制器如何使用x单位来求和所有参数。

我尝试了以下操作,但是不确定如何模拟所有接口依赖项注入类。请找到以下控制器。

当我运行此测试时,_userManager用户列表为null。请帮助我,有关如何将数据发送到_usermanger

//This below m controller for which i need to write a x unit testcase 
   public UsersController(
        UserManager<ApplicationUser> userManager,
        ApplicationDbContext applicationDbContext,
        IEmailSender emailService,
        IConfiguration configuration)
    {
        _userManager = userManager;
        _applicationDbContext = applicationDbContext;
        _emailService = emailService;
        _configuration = configuration;
    }
   //controller Method for which i need to write a test case 
   [HttpGet]
    [Route("User")]
    [AllowAnonymous]
    public async Task<IActionResult> AppUser([FromQuery] string username)
    {
        var user = await _userManager.FindByNameAsync(username);
      return ok(user);
    }

  // This is my test message which I'm writing 
   ApplicationUser testUser = new ApplicationUser { UserName = "testuser1"};     
        var mockStore = new Mock<IUserStore<ApplicationUser>>();
        var mockUserManager = new Mock<UserManager<ApplicationUser>> 
       (mockStore.Object, null, null, null, null, null, null, null, null);
        mockStore.Setup(x => x.CreateAsync(appuser, 
       It.IsAny<CancellationToken>()))
      .Returns(Task.FromResult(IdentityResult.Success));
        mockStore.Setup(x => x.FindByNameAsync(testUser.UserName, It.IsAny<CancellationToken>()))
                     .Returns(Task.FromResult(testUser));
        var fakeEmailSender = new Mock<IEmailSender>();
        var fakeConfiguration = new Mock<IConfiguration>();

        var Controller = new UsersController(mockUserManager.Object, 
          context, fakeEmailSender.Object, fakeConfiguration.Object);
        var res = Controller.AppUser("testuser1");
     }

0 个答案:

没有答案