测试自定义用户配置文件以用于ASP成员资格

时间:2011-03-02 16:51:21

标签: c# unit-testing model-view-controller moq

我刚刚完成了对我的MVC项目实现基本的asp成员资格,我正在寻找一些测试。我在模拟提供程序时遇到了一些初步问题,但现在已经排序了。显然,当提供者被模拟时,没有数据存在,也不能添加任何数据,但是不能直接模拟配置文件,因为每次需要用户配置文件时都会创建配置文件。我不确定如何测试这些(显然)当调用配置文件时它会返回null。

例如:

使用DI我的存储库注入:

    public AccountMembershipService(MembershipProvider provider)
    {
        _provider = provider ?? Membership.Provider;

    }

让我们以创建用户方法

为例
    public MembershipCreateStatus CreateUser(string userName, string password, string email, string passwordQuestion, string passwordAnswer)
    {
        if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
        if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");
        if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");

        MembershipCreateStatus status;
        _provider.CreateUser(userName, password, email, passwordQuestion, passwordAnswer, true, null, out status);

        if (status == MembershipCreateStatus.Success)
        {
            UserProfile profile = UserProfile.GetProfile(userName);
            profile.IPAddress = "0.0.0.0";
            profile.Save();
        }
        return status;
    }

.CreateUser完美运行(就模拟而言)但是当涉及到GetProfile时,显然没有配置文件存在,所以它只是错误。关于我如何能够对此进行测试的任何想法?

我已经盯着这个好几个小时了,任何帮助都会非常感激!!

1 个答案:

答案 0 :(得分:1)

看一下使用Pex Moles替换Base UserProfile类的Create方法。

另一种选择可能是创建一个调用GetProfile()的服务对象,然后可以将其抽象化,并在运行时将一个具体类注入AccountMembershipService,或者在单元测试期间传递给构造函数。