我正在做一个 ASP.Net MVC2 项目,我想对其进行一些单元测试。我试图测试我的 LogOnController 并且遇到了一些困难。在我的 LogOnController 中,我使用 AccountMembershipService 作为,
AccountMembershipService MembershipService = new AccountMembershipService();
if (MembershipService.ValidateUser(model.UserName, model.Password)){
............
..........
}
我正在使用 MOQ 框架,我想知道如何模拟 AccountMembershipService。即使我给出了正确的用户名和密码“ MembershipService.ValidateUser(model.UserName, model.Password)
”总是返回错误。所以你们中的任何人都知道如何做到这一点..
顺便说一句,我尝试过属性注入。但我一直收到以下错误..
“非虚拟(在 VB 中可覆盖)成员的设置无效:x => x.ValidateUser(.validUserName, .validPassword)”。
它来自“ stubService.Setup(x => x.ValidateUser(model.UserName, model.Password)).Returns(true);
”行。
这是我的代码..
[TestMethod]
public void TestLogOn_ValidUserNameAndPassword()
{
var controller = new LogOnController();
var request = new Mock<HttpRequestBase>(MockBehavior.Loose);
var model = new LogOnModel();
var context = new Mock<HttpContextBase>(MockBehavior.Loose);
var stubService = new Mock<AccountMembershipService>();
model.UserName = "xxxxx";
model.Password = "123";
context.SetupGet(x => x.Request).Returns(request.Object);
controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
stubService.Setup(x => x.ValidateUser(validUserName, validPassword)).Returns(true);
Assert.IsTrue(stubService.Object.ValidateUser(model.UserName, model.Password));
}