2011-08-31 19 views
1

我從來沒有使用任何模擬框架,實際上是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)>.

我在做什麼錯了?

謝謝

+0

你試過'controller.ViewBag [「UserEmail」]'? –

+0

這根本不起作用,試了一下,得到一個異常'測試方法HomeControllerTest.Index_Action_Test拋出異常: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:無法將索引用[]應用於類型爲'System.Dynamic.DynamicObject '' – Burjua

回答

4

簡單 - 你不要做正確的行爲部分。最前一頁應該叫控制器Index()動作,然後斷言ViewBag.UserEmail正確性

// Act 
     controller.Index(); 
     string result = controller.ViewBag.UserEmail; 

順便說一句,建議 - 使用ViewBag不是好的做法。定義ViewModels代替

+0

是的,你是對的,它現在有效,非常感謝。我確實使用ViewModels,ViewBag在這裏是爲了簡單:) – Burjua