c# - 模拟 UserPrincipal

标签 c# .net tdd

我有一个类可以处理交换邮箱的密码更改和过期检查。 我在 UserPrincipal 上检查 LastPasswordSet。

那么 TDD 呢?

我想通过编写一些测试来检查我的类(class)是否正确处理了密码检查。但是我无法理解如何模拟 UserPrincipal.FindByIdentity(principalContext, [some username])。

我将要编写一个方法,如果密码在过去 90 天内被更改,则返回 true/false。所以我想模拟 UserPrincipal,这样我就可以在我的测试中设置 LastPasswordSet 返回值,只是为了检查我将要为“密码需要更改通知”编写的逻辑。

最佳答案

我意识到这是一个旧帖子,但最近我遇到了与原始发布者相同的问题,在阅读答案后,我认为我必须做同样的事情。我不想让其他人像我一样看到这篇文章而浪费宝贵的时间,所以我决定真正回答这篇文章。

在意识到没有简单的方法来包装 UserPrincipal 功能,也没有像建议的那样依赖集成或端到端测试后,我想起了有一种模拟静态类的方法。话虽如此,下面是使用 Telerik JustMock 的具体方法。 .

private void MockUserPrincipal()
    {
        //Mock principal context
        var context = Mock.Create<PrincipalContext>((action) => action.MockConstructor());

        //Mock user principal
        var user = Mock.Create(() => new UserPrincipal(context));           

        //Mock the properties you need
        Mock.Arrange(() => user.Enabled).Returns(true);
        Mock.Arrange(() => user.UserPrincipalName).Returns("TestUser");
        Mock.Arrange(() => user.LastPasswordSet).Returns(DateTime.Now);

        //Mock any functions you need
        Mock.Arrange(() => user.IsAccountLockedOut()).Returns(false);

        //Setup static UserPrincipal class
        Mock.SetupStatic<UserPrincipal>();

        //Mock the static function you need
        Mock.Arrange(() => UserPrincipal.FindByIdentity(Arg.IsAny<PrincipalContext>(), Arg.AnyString)).Returns(user);  

        //Now calling UserPrincipal.FindByIdentity with any context and identity will return the mocked UserPrincipal
    }

关于c# - 模拟 UserPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7144959/

相关文章:

C# 基于json文件的数据库

xcode - 具有多目标项目的 XCTest

.net - 另一个 "could not load file or assembly ... or one of its dependencies. The system cannot find the file specified"

c# - 通过 XML 属性扩展 ASP.Net TreeView 中的节点

c# - DataView RowFilter 中的撇号

c# - 以编程方式将 WPF DataGrid 列宽定义为 100%

c# - 如何在wp7中的独立存储中保存对象列表

java - 创建测试数据 : domain builder

java - JUnit 中用于 ShoppingCart 的无序执行测试

c# - 简单的评估表不显示在表中