【问题标题】:How to use Moq framework correctly - basic question如何正确使用 Moq 框架 - 基本问题
【发布时间】: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:&lt;test@test.com&gt;. Actual:&lt;(null)&gt;.

我做错了什么?

谢谢

【问题讨论】:

  • 你试过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


【解决方案1】:

很简单——你没有正确地做动作部分。首先你应该调用控制器的Index() action,然后断言 ViewBag.UserEmail 正确性

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

顺便说一句,建议 - 使用 ViewBag 不是好习惯。改为定义 ViewModel

【讨论】:

  • 是的,你是对的,它现在可以工作了,非常感谢。我确实使用 ViewModels,ViewBag 在这里是为了简单起见:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多