简体   繁体   English

如何对 Asp.Net MVC Identity UserManager.ChangePasswordAsync 进行单元测试

[英]How to Unit Test Asp.Net MVC Identity UserManager.ChangePasswordAsync

I am writing unit Test cases for my Home Controller, in Home controller i have Action Method called MyProfile which calls ChangePasswordAsync Method in UserManager class.我正在为我的家庭控制器编写单元测试用例,在家庭控制器中,我有一个名为 MyProfile 的操作方法,它在 UserManager 类中调用 ChangePasswordAsync 方法。 How to test application User manager如何测试应用程序用户管理器

Below is my Controller code下面是我的控制器代码

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> MyProfile(ChangePasswordViewModel model)
{
  if (!ModelState.IsValid)
     {
       return View(model);
     }
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
    if (result.Succeeded)
       {
     var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
      if (user != null)
        {
      await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
       }
      var verification_uid = Guid.NewGuid().ToString();


        }

You don't.你没有。 This is a prime example of testing the framework, which you shouldn't be doing.这是测试框架的一个主要示例,您不应该这样做。 You need to write tests for your application code, not for Identity or any other part of ASP.NET.您需要为应用程序代码编写测试,而不是为 Identity 或 ASP.NET 的任何其他部分编写测试。 That code is already well-tested by Microsoft.该代码已经过 Microsoft 的充分测试。 You can safely assume that calling ChangePasswordAsync will in fact change the user's password.您可以放心地假设调用ChangePasswordAsync实际上会更改用户的密码。 Otherwise, the Identity release you're running would have failed its testrun and never been released.否则,您正在运行的 Identity 版本将无法通过测试并且永远不会发布。

I am able to test my controller code in a test.我能够在测试中测试我的控制器代码。 It is simple and does the job but keep in mind that the controller code is application tier and is more or less a black box to my test... meaning ChangePasswordAsync is working as expected - under the covers.它很简单并且可以完成工作,但请记住,控制器代码是应用程序层,对我的测试来说或多或少是一个黑盒子……这意味着 ChangePasswordAsync 正在按预期工作 - 在幕后。 I am also having to write my own test code to get a list of users by role in my test to add a claim so I am still learning.我还必须编写自己的测试代码,以按我的测试中的角色获取用户列表以添加声明,因此我仍在学习。 Hope this helps!希望这可以帮助!

<TestMethod()> Public Sub Index()

        ' Arrange
        Dim controller As New HomeController()

        ' Act
        Dim result As ViewResult = DirectCast(controller.Index(), ViewResult)

        ' **Assert that your change password returns the expected model**
        Assert.IsNotNull(result)
    End Sub

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

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