1

I've never used any Mock frameworks and actually new to ASP.NET MVC, testing and all this related stuff.

I'm trying to figure out how to use Moq framework for testing, but can't make it work. that's what I have at the moment: My repository interface:

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);
}

My Controller constuctor, I'm using Ninject for injection, it works fine

private readonly IUserRepository _userRepository;

public HomeController(IUserRepository userRepository) {
    _userRepository = userRepository;
}

Simplest method in controller:

public ActionResult Index() {
    ViewBag.UserEmail = _userRepository.GetUserEmail();
    return View();
}

And my test method:

    [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);
    }

I assume that this test must pass, but it fails with message Assert.AreEqual failed. Expected:<[email protected]>. Actual:<(null)>.

What am I doing wrong?

Thanks

2
  • Have you tried controller.ViewBag["UserEmail"]? Commented Aug 31, 2011 at 12:27
  • This doesn't work at all, tried it, got an exception Test method HomeControllerTest.Index_Action_Test threw exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot apply indexing with [] to an expression of type 'System.Dynamic.DynamicObject' Commented Aug 31, 2011 at 12:31

1 Answer 1

4

Simple - you do not do Act part correctly. Fisrt you should call Index() action of the controller, and then Assert ViewBag.UserEmail correctness

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

By the way, advice - Using ViewBag is not the good practice. Define ViewModels instead

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you are right, it works now, thanks a lot. And I do use ViewModels, ViewBag is here for simplicity:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.