Moq 成员变量不会因无效设置而抛出错误

Moq member variables not throwing error for invalid setup

我故意尝试通过错误的最小起订量设置,我预计会出现错误。我将 class 传递到我的设置方法,我希望实例变量符合特定条件。由于我创建了 class 的新实例,我预计会出现错误,因为所有实例变量都是 null。但是,什么也没有抛出?

        var mockParams = new object[] { mockRequestRepo.Object, mockNotificationSvc.Object, mockLogger.Object, mockNotificationBuilder.Object };
        var mockActivityReportBO = new Mock<ActivityReport>(mockParams);
        // Instance variables for class.
        mockActivityReportBO.Setup(x => x.AddReport(It.Is<ActivityReport>(
            x => x.Title == It.IsAny<string>()
            && x.Limits == It.IsAny<string>()
            && x.Description == It.IsAny<string>()
            && x.DueDate == It.IsInRange(DateTime.Now.AddDays(12), DateTime.MaxValue, Range.Inclusive)
            && x.CountyNumber == It.IsInRange(1, 5, Range.Inclusive)
            && x.ActivityReportID == It.IsInRange(1, 12, Range.Inclusive)
        )));
        var report = new ActivityReport();
        // No error thrown
        mockActivityReportBO.Object.AddReport(report);

首先,根据设计,它不会抛出异常,除非模拟的行为是严格的。

引用Moq Quick start: Customizing Mock Behavior

Make mock behave like a "true Mock", raising exceptions for anything that doesn't have a corresponding expectation: in Moq slang a "Strict" mock; default behavior is "Loose" mock, which never throws and returns default values or empty arrays, enumerables, etc. if no expectation is set for a member

注意:强调我的

var mock = new Mock<IFoo>(MockBehavior.Strict);

其次,Setup 没有通过在 Setup 表达式之外创建参数匹配器来正确完成

mockActivityReportBO.Setup(_ => _.AddReport(It.Is<ActivityReport>(
        x => x.Title == It.IsAny<string>()
        && x.Limits == It.IsAny<string>()
        && x.Description == It.IsAny<string>()
        && x.DueDate == It.IsInRange(DateTime.Now.AddDays(12), DateTime.MaxValue, Range.Inclusive)
        && x.CountyNumber == It.IsInRange(1, 5, Range.Inclusive)
        && x.ActivityReportID == It.IsInRange(1, 12, Range.Inclusive)
    )
));

引用Moq Quick start: Matching Arguments

更新

I would like the mock exception thrown when I pass a parameter, that contains data outside the setup. For example, If I try to call add report, and I pass a report object where the member variable Title = null, I would like an exception thrown.

明确说明会发生什么,并告诉设置程序在发生这种情况时抛出异常

例如

mockActivityReportBO
    .Setup(x => x.AddReport(It.Is<ActivityReport>(y => y.Title == null)))
    .Throws<InvalidOperationException>(); //<-- replace with desired Exception

当您将成员变量 Title = null 的报表对象传递给 mock 时,上面的代码将抛出异常。 (当然使用默认行为模式"Loose"。不是"Strict")