Moq异常:验证带参数的方法调用

时间:2010-06-25 09:18:48

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

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

测试方法Baigent .DoNation.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");

请帮忙!

3 个答案:

答案 0 :(得分:1)

例外情况告诉您,您正试图覆盖非虚拟成员,这是不可能的。

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

请参阅here for a more detailed explanation

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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