ASP.NET Core 中的单元测试自定义密码验证器

2023-12-10

我有一个覆盖 PasswordValidator 的 CustomPasswordValidator.cs 文件

 public class CustomPasswordValidator : PasswordValidator<AppUser>
    {   //override the PasswordValidator functionality with the custom definitions
        public override async Task<IdentityResult> ValidateAsync(UserManager<AppUser> manager, AppUser user, string password)
        {
            IdentityResult result = await base.ValidateAsync(manager, user, password);

            List<IdentityError> errors = result.Succeeded ? new List<IdentityError>() : result.Errors.ToList();

            //check that the username is not in the password
            if (password.ToLower().Contains(user.UserName.ToLower()))
            {
                errors.Add(new IdentityError
                {
                    Code = "PasswordContainsUserName",
                    Description = "Password cannot contain username"
                });
            }

            //check that the password doesn't contain '12345'
            if (password.Contains("12345"))
            {
                errors.Add(new IdentityError
                {
                    Code = "PasswordContainsSequence",
                    Description = "Password cannot contain numeric sequence"
                });
            }
            //return Task.FromResult(errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray()));
            return errors.Count == 0 ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
        }
    }

我是使用 Moq 和 xUnit 的新手。我正在尝试创建一个单元测试,以确保产生正确数量的错误(显示工作代码,以及在注释中产生错误的代码):

//test the ability to validate new passwords with Infrastructure/CustomPasswordValidator.cs 
        [Fact]
        public async void Validate_Password()
        {
            //Arrange
            <Mock><UserManager<AppUser>> userManager = new <Mock><UserManager<AppUser>>(); //caused null exception, use GetMockUserManager() instead
            <Mock><CustomPasswordValidator> customVal = new <Mock><CustomPasswordValidator>(); //caused null result object use customVal = new <CustomPasswordValidator>() instead
            <AppUser> user = new <AppUser>
            user.Name = "user" 
            //set the test password to get flagged by the custom validator
            string testPwd = "Thi$user12345";

            //Act
            //try to validate the user password
            IdentityResult result = await customVal.ValidateAsync(userManager, user, testPwd);

            //Assert
            //demonstrate that there are two errors present
            List<IdentityError> errors = result.Succeeded ? new List<IdentityError>() : result.Errors.ToList();
            Assert.Equal(errors.Count, 2);
        }

//create a mock UserManager class
        private Mock<UserManager<AppUser>> GetMockUserManager()
        {
            var userStoreMock = new Mock<IUserStore<AppUser>>();
            return new Mock<UserManager<AppUser>>(
                userStoreMock.Object, null, null, null, null, null, null, null, null);
        }

错误发生在 IdentityResult 行上,表明我无法将 Mock 转换为 UserManager,也无法将 Mock 转换为 AppUser 类。

编辑:更改为包含在 ASP.NET core 中模拟 UserManagerClass 所需的 GetMockUserManager() (模拟新的 Microsoft Entity Framework Identity UserManager 和 RoleManager)


对于起订量,您需要致电.Object在模拟上获取模拟对象。您还应该使测试异步并等待被测方法。

您还模拟了被测试的主题,在这种情况下,这会导致被测试的方法在调用时返回 null,因为它没有被正确设置。此时您基本上正在测试模拟框架。

创建被测主题的实际实例CustomPasswordValidator并进行测试,模拟被测对象的显式依赖关系以获得所需的行为。

public async Task Validate_Password() {

    //Arrange
    var userManagerMock = new GetMockUserManager();
    var subjetUnderTest = new CustomPasswordValidator();
    var user = new AppUser() {
        Name = "user" 
    }; 
    //set the test password to get flagged by the custom validator
    var password = "Thi$user12345";

    //Act
    IdentityResult result = await subjetUnderTest.ValidateAsync(userManagerMock.Object, user, password);


    //...code removed for brevity

}

Read 起订量快速入门更熟悉如何使用最小起订量。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET Core 中的单元测试自定义密码验证器 的相关文章

  • ScrollableControl 在整个控件周围绘制边框

    我正在构建基于的自定义用户控件ScrollableControl 现在我正在尝试在控件周围添加边框 类似于 DataGridView 的边框 我可以使用以下方法绘制边框 e Graphics TranslateTransform AutoS
  • C# SMO 远程数据库备份到本地机器

    我有一个执行 SQL 数据库备份和恢复的应用程序 这在本地计算机上运行良好 但是如果我针对另一台计算机上托管的 SQL 服务器运行此应用程序 则会出现以下错误 Microsoft SqlServer Management Smo Faile
  • 不要覆盖 Azure Blob 存储

    我有一种将文件添加到 Azure Blob 存储的方法 问题是我试图指定一个条件 在该条件下它不会覆盖 blob 而只是添加到其中 我正在尝试使用参数访问条件 但是 VS 说这个方法不能采用两个参数 async void archiveNe
  • ICSharpCode.Decompiler + Mono.Cecil -> 如何为单个方法生成代码?

    我可以使用 Mono Cecil 和 ICSharpCode Decompiler 生成类型或程序集的代码 但是 如果我尝试为单个方法生成代码 我将收到错误 对象引用未设置为对象的实例 你们能给我任何关于这个的提示吗 提前感谢您的所有帮助
  • 使用 C# 启动 Outlook

    我可以让 C 在代码中启动 Outlook 吗 在 VB6 中 我们使用对象 Outlook Application 并编写 Set oOutlook CreateObject Outlook Application Set oNameSp
  • JUnit 集成测试的“IT.java”文件名后缀(而不是“Test.java”)是否是一种约定? [关闭]

    Closed 这个问题是基于意见的 help closed questions 目前不接受答案 我习惯于用一个名称来命名我的 JUnit 集成测试 Test java最后例如DatabaseConnectionTest java并将它们放在
  • std::istringstream >> 使奇怪的行为加倍

    下面的代码打印0在 mac osx 上使用 clang 其他地方都会打印5 clang https ideone com mVgpzS gcc https ideone com oZ0hy6 include
  • 如何转换 UTF-8 <-> UTF16 可移植

    有没有一种简单 可移植的方法 至少是 win32 linux 将 UTF 16 转换为 UTF 8 并返回 最好使用升压 谢谢你的帮助 托比亚斯 Both libiconv http www gnu org software libicon
  • Makefile:如何正确包含头文件及其目录?

    我有以下 makefile CC g INC DIR StdCUtil CFLAGS c Wall I INC DIR DEPS split h all Lock o DBC o Trace o o cpp DEPS CC o lt CFL
  • 安全移动 C++ 对象

    我听到过一些警告 不要通过以下方式将对象运送到另一个内存位置memcpy 但不知道具体原因 除非它包含的成员做了依赖于内存位置的棘手事情 否则这应该是完全安全的 或者不是 编辑 预期的用例是像这样的数据结构vector 它存储对象 不是po
  • 如何检查我的程序是否有数据通过管道传输到其中

    我正在编写一个应该通过标准输入读取输入的程序 所以我有以下结构 FILE fp stdin 但是 如果用户没有将任何内容通过管道传输到程序中 这就会挂起 我如何检查用户是否确实将数据通过管道传输到我的程序中 例如 gunzip c file
  • 从 ASP.NET Web API 返回 HTML

    如何从 ASP NET MVC Web API 控制器返回 HTML 我尝试了下面的代码 但由于未定义 Response Write 而出现编译错误 public class MyController ApiController HttpP
  • ASP Net Core 属性路由和双正斜杠

    正如所指出的here https stackoverflow com a 20524044 3129340 URL 中包含双斜杠是有效的 我有一个使用属性路由的 ASP Net Core 项目 一个名为GroupController用于处理
  • 在另一个类中使用一个类对象?

    我正在用 c 制作应用程序 在该应用程序中 我有一个类DataCapture cs 在同一个应用程序中 我有另一个类Listner cs 在 Listner cs 类中 我想使用以下对象DataCapture cs不创建新对象DataCap
  • 通用 lambda 的数量

    可以通过访问非泛型 lambda 的数量来推断其数量operator template
  • 在 C++ 中运行 python [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 我有一个用 C 编写的应用程序和一个测试系统 也是用 C 编写的 测试系统非常复杂并且很难改变 我只想做一些小的改变 我的班级是这样的
  • 使用智能指针在大型对象集合中创建多个索引

    我正在为一个大型对象集合创建多个索引 即使用不同的键 对象可以改变 集合可以缩小和增长 到目前为止我的想法 保留某种指向对象的指针的多个集合 使用set代替map以获得更好的封装 使用 unordered set 可以很好地扩展大型数据集
  • 以编程方式将 UserControl 从 ContentControl 移动到另一个 ContentControl

    在 WPF 应用程序中 我想在代码中将 UserControl 从 ContentControl 移动到另一个控件 myContentControl2 Content myUserControl 在这种情况下我得到一个错误 指定的元素已经是
  • 如何同时正确使用管道和信号?

    我有 2 个孩子 我想将信号从孩子发送到父母 并将答案 随机数 为什么 为什么不 命名管道从父母发送到每个孩子 我有这个代码 include
  • 布尔实现的atomicCAS

    我想弄清楚是否存在错误答案 https stackoverflow com a 57444538 11248508 现已删除 关于Cuda like的实现atomicCAS for bool是 答案中的代码 重新格式化 static inl

随机推荐