【发布时间】:2023-03-22 17:56:01
【问题描述】:
我从未使用过任何 Mock 框架,实际上是 ASP.NET MVC、测试和所有这些相关内容的新手。
我试图弄清楚如何使用 Moq 框架进行测试,但无法使其工作。这就是我目前所拥有的:我的存储库界面:
public interface IUserRepository {
string GetUserEmail();
bool UserIsLoggedIn();
ViewModels.User CurrentUser();
void SaveUserToDb(ViewModels.RegisterUser viewUser);
bool LogOff();
bool LogOn(LogOnModel model);
bool ChangePassword(ChangePasswordModel model);
}
我的 Controller 构造器,我正在使用 Ninject 进行注入,它工作正常
private readonly IUserRepository _userRepository;
public HomeController(IUserRepository userRepository) {
_userRepository = userRepository;
}
控制器中最简单的方法:
public ActionResult Index() {
ViewBag.UserEmail = _userRepository.GetUserEmail();
return View();
}
还有我的测试方法:
[TestMethod]
public void Index_Action_Test() {
// Arrange
string email = "test@test.com";
var rep = new Mock<IUserRepository>();
rep.Setup(r => r.GetUserEmail()).Returns(email);
var controller = new HomeController(rep.Object);
// Act
string result = controller.ViewBag.UserEmail;
// Assert
Assert.AreEqual(email, result);
}
我假设这个测试必须通过,但它失败并显示消息Assert.AreEqual failed. Expected:<test@test.com>. Actual:<(null)>.
我做错了什么?
谢谢
【问题讨论】:
-
你试过
controller.ViewBag["UserEmail"]吗? -
这个完全不行,试了一下,出现异常
Test method HomeControllerTest.Index_Action_Test threw exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject'
标签: asp.net-mvc testing dependency-injection mocking moq