我從來沒有使用任何模擬框架,實際上是ASP.NET MVC的新手,測試和所有這些相關的東西。如何正確使用Moq框架 - 基本問題
我想弄清楚如何使用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);
}
我的控制器constuctor,我使用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 = "[email protected]";
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:<[email protected]>. Actual:<(null)>.
我在做什麼錯了?
謝謝
你試過'controller.ViewBag [「UserEmail」]'? –
這根本不起作用,試了一下,得到一個異常'測試方法HomeControllerTest.Index_Action_Test拋出異常: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:無法將索引用[]應用於類型爲'System.Dynamic.DynamicObject '' – Burjua