我有以下帐户控制器
public class AccountController : Controller
{
public IMembershipService MembershipService { get; set; }
protected override void Initialize(RequestContext requestContext)
{
if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
base.Initialize(requestContext);
}
public AccountController(IMembershipService membership)
{
MembershipService = membership;
}
[HttpPost]
public ActionResult Login(LoginModel model, string ReturnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.EmailorUserName, model.Password))
{
.....
}
}
}
来自我的单元测试项目我想模拟登录
public class AccountControllerTest2
{
[Test]
public void Login_UserCanLogin()
{
string returnUrl = "/Home/Index";
string userName = "user1";
string password = "password1";
Mock<AccountMembershipService> Membership = new Mock<AccountMembershipService>();
AccountController Controller = new AccountController(Membership.Object);
var model = new LoginModel
{
EmailorUserName = userName,
Password = password
};
var result = Controller.Login(model, returnUrl) as RedirectResult;
Assert.NotNull(result);
Assert.AreEqual(returnUrl, result.Url);
}
}
我的主应用程序中的web配置使用custommembership provider
<membership defaultProvider="CustomMembershipProvider">
<providers>
<clear />
<add name="CustomMembershipProvider" type="QUBBasketballMVC.Infrastructure.CustomMembershipProvider" connectionStringName="UsersContext" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
我一直收到此错误
QUBBasketballMVC.Tests.Controllers.AccountControllerTest.Login_UserCanLogin: System.Web.Management.SqlExecutionException:执行SQL文件&#39; InstallCommon.sql&#39;期间发生错误。 SQL错误号为5123,并且SqlException消息为:CREATE FILE在尝试打开或创建物理文件时遇到操作系统错误5(访问被拒绝。)C:\ PROGRAM FILES(X86)\ NUNIT 2.6。 3 \ BIN \ APP_DATA \ ASPNETDB_TMP.MDF&#39 ;. CREATE DATABASE失败。无法创建列出的某些文件名。检查相关错误。 创建ASPNETDB_7b94db5a0b5b4fbbbe22fa8e91e4cc68数据库......
答案 0 :(得分:1)
您似乎仍在初始化真实会员数据库,这意味着MembershipService
尚未完全被模拟。您不应该将成员资格配置添加到单元测试中,因为您打算完全嘲笑它。
您几乎肯定想要将接口模拟为服务抽象IMembershipService
,即:
Mock<IMembershipService> Membership = new Mock<IMembershipService>();
另外,懒惰的初始化代码
if (MembershipService == null)
MembershipService = new AccountMembershipService();
从测试的角度来看,并不理想,因为它意味着控制器有两种操作模式,它可以创建MembershipService
本身,也可以接受一个作为构造函数依赖。
作为替代方案,您可以考虑使用IoC
框架来管理依赖生命周期,这样只需要测试一组代码。