我正在尝试使用 Moq 编写单元测试以验证注册是否成功。我的测试如下:
[TestMethod()]
public void RegisterTest()
{
//Arrange
var MockRepo = new Mock<IDataRepo>() ;
RegisterModel model = new RegisterModel
{
ConfirmPassword = "SamePassword",
Email = "myemail@address.com",
FirstName = "MyFirstName",
LastName = "MyLastName",
MiddleName = "MyMiddleName",
Password = "SamePassword"
};
MockRepo.Setup(ctx => ctx.Add(model)).Verifiable("Nothing was added to the Database");
//Act
AccountController target = new AccountController(MockRepo.Object);
//Assert
ActionResult actual = target.Register(model);
MockRepo.Verify(ctx => ctx.Add(It.IsAny<RegisterModel>()));
Assert.IsInstanceOfType(actual, typeof(ViewResult));
}
但它失败并出现以下错误
对模拟的预期调用至少一次,但从未执行过:ctx => ctx.Add(It.IsAny())
但是,当我调试测试方法时,我注意到实际上调用了 Add(T) 方法。MOQ dll 版本为 v4.0
更新 帐户控制器:
public class AccountController : Controller
{
private IDataRepo _repo;
public AccountController(IDataRepo Repo)
{
_repo = Repo;
}
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
User user = _repo.Users.Where(u => u.Email == model.Email).FirstOrDefault();
if (user == null)
{
_repo.Add(new User
{
Email = model.Email,
Password = model.Password,
FirstName = model.FirstName,
LastName = model.LastName,
MiddleName = model.MiddleName
});
return View("RegistrationSuccess");
}
else
{
ModelState.AddModelError("UserExists", "This Email already Exists");
}
}
return View(model);
}
}