【问题标题】:Moq Exception: Verifying a method call that takes parametersMoq 异常:验证带参数的方法调用
【发布时间】:2011-03-08 05:01:46
【问题描述】:

我想测试我的控制器中 _eventManager 上的“创建”方法是否被调用。当我运行测试时,出现以下异常:

测试方法 Baigent.TheDoNation.Application.Tests.EventControllerTest.Create_Post_IfModelIsValidRedirectToSuccessfullyCreatedViewOccurs 抛出异常:System.ArgumentException:不可覆盖成员上的无效设置: m => m.CreateEvent(It.IsAny(), It.IsAny())。

控制器的代码是:

    public ActionResult Create(Event eventObject, FormCollection collection)
    {
        if (ModelState.IsValid)
        {
            _eventManager.CreateEvent(eventObject, User.Identity.Name);

            return RedirectToAction("SuccessfullyCreated", new { });
        }

        // Invalid - redisplay form with errors
        return View(GetEventViewModel(eventObject));
    }

_eventManager 字段在构造函数中设置。我的测试是:

        var eventManagerMock = new Mock<EventManager>(new FakeEventsRepository());
        eventManagerMock.Setup(m => m.CreateEvent(It.IsAny<Event>(), It.IsAny<String>())).Verifiable("No call to CreateEvent on the EventManager was made");

        var eventController = new EventController(eventManagerMock.Object);

        var newEvent = new Event {Name = "Test Event", Date = DateTime.Now, Description = "Test description"};

        // Act
        var result = eventController.Create(newEvent, new FormCollection()) as RedirectToRouteResult;

        // Assert
        eventManagerMock.Verify(m => m.CreateEvent(It.IsAny<Event>(), It.IsAny<String>())); 

        Assert.IsNotNull(result, "RedirectToRouteResult should be returned");
        Assert.AreEqual("SuccessfullyCreated", result.RouteValues["action"], "Redirect should be to SuccessfullyCreated view");

请帮忙!

【问题讨论】:

    标签: asp.net-mvc unit-testing testing moq


    【解决方案1】:

    异常告诉您您正在尝试覆盖一个非虚拟成员,这是不可能的。

    Moq(以及 Rhino Mocks 和 NMock)只能覆盖虚拟成员(包括纯接口成员)。

    here for a more detailed explanation

    【讨论】:

      【解决方案2】:

      您要么必须将方法设为 Virtual,要么您需要定义一个具有 CreateEvent() 方法的接口,然后模拟该接口:]

      您现在想要模拟一个 Moq 没有直接权限覆盖它的方法。

      【讨论】:

        【解决方案3】:

        Moq 只能模拟您的 EventManager 类型的虚拟成员。您应该考虑提取IEventManager 接口,或者将CreateEvent 方法设为虚拟。

        【讨论】:

        • 谢谢,你是对的。实际上,我在发帖 10 分钟后得出了这个结论——我认为这是一篇仓促的帖子。
        猜你喜欢
        • 2011-07-11
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-09
        • 1970-01-01
        相关资源
        最近更新 更多