据我所知,MOQ框架在这个例子中并没有真正帮助过,但也许你可以帮忙......
我有一个方法,它使用try / catch,只要抛出异常就会调用通知方法。我要做的是创建一个集成/单元测试,检查以确保在抛出任何异常时调用SendNotification。
待测方法:
public virtual void MonitorIntradayBuilds(IIntradayBuilds intradayBuilds)
{
try
{
var intradayBuildFound = intradayBuilds.CheckForIntradayBuilds();
if (intradayBuildFound && !IntradayBuildsComplete && !DailyBuildsFound)
{
IntradayBuildsComplete = intradayBuilds.StartIntradayBuilds();
//should start daily builds?
}
}
catch (Exception ex)
{
SendNotification("MonitorIntradayBuilds threw an exception", ex);
}
}
测试用例:
[Test]
public void it_should_notify_developers_immediately_if_there_is_a_problem_when_checking_for_intraday_builds()
{
//Arrange
var mockDua = new Mock<DUA>();
var mockIB = new Mock<IIntradayBuilds>();
//Act
mockIB.Setup(x => x.CheckForIntradayBuilds()).Throws(new Exception());
mockDua.Object.MonitorIntradayBuilds(mockIB.Object);
//Assert
mockDua.Verify(x => x.SendNotification(It.IsAny<string>(), It.IsAny<Exception>()), Times.Once);
}
我继续点击Moq.MockException然后看到SendNotification&#34;期望在模拟上调用一次,但是是0次...&#34;
我已尝试在测试用例中使用[ExpectedException]属性,但无济于事。它使测试通过,但仍然没有调用SendNotification方法。
有什么想法吗?
答案 0 :(得分:2)
解决了它。
原来你需要在你正在模拟的系统测试中设置CallBase属性。
现在是测试用例:
[Test]
public void it_should_notify_developers_immediately_if_there_is_a_problem_when_checking_for_intraday_builds()
{
//Arrange
var mockDua = new Mock<DUA>();
var mockIB = new Mock<IIntradayBuilds>();
mockDua.CallBase = true; // <<<< Added this line!
//Act
mockIB.Setup(x => x.CheckForIntradayBuilds()).Throws(new Exception());
mockDua.Object.MonitorIntradayBuilds(mockIB.Object);
//Assert
mockDua.Verify(x => x.SendNotification(It.IsAny<string>(), It.IsAny<Exception>()), Times.Once);
}
希望其他人觉得有用:)