【发布时间】:2017-11-29 20:28:12
【问题描述】:
我正在尝试在要测试的方法中模拟服务调用。
方法体如下所示:
public string OnActionException(HttpActionContext httpRequest, Exception ex)
{
var formattedActionException = ActionLevelExceptionManager.GetActionExceptionMessage(httpRequest);
var mainErrorMessage = $"[{formattedActionException.ErrorId}]{formattedActionException.ErrorMessage}, {ex.Message}";
this.LogError(mainErrorMessage, ex);
if (this._configuration.MailSupportOnException)
Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> Stack trace: {ex.StackTrace.ToString()}"));
return $"(ErrID:{formattedActionException.ErrorId}) {formattedActionException.ErrorMessage} {formattedActionException.KindMessage}";
}
我想在测试中模拟的是:
Task.Run(async () => await this._mailService.SendEmailForThrownException(this._configuration.SupportEmail, $"{mainErrorMessage} ---> 堆栈跟踪:{ex.StackTrace.ToString()}" ));
测试方法如下:
[TestMethod]
public void We_Send_System_Exception_On_Email_If_Configured_In_Settings()
{
// arrange
this._configurationWrapperMock.Setup(cwm => cwm.MailSupportOnException)
.Returns(true);
this._mailServiceMock.Setup(msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult(0));
// act
var logger = new ApiLogger(this._configurationWrapperMock.Object, this._mailServiceMock.Object);
logger.OnActionException(
new HttpActionContext(
new HttpControllerContext()
{
Request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new System.Uri("https://www.google.bg/")
}
},
new ReflectedHttpActionDescriptor() { }
),
new System.Exception());
// assert
this._mailServiceMock.Verify(
msm => msm.SendEmailForThrownException(It.IsAny<string>(), It.IsAny<string>()),
Times.Once);
}
问题是该方法从未被调用,所以我的断言失败了。
编辑:我可以将我的问题改为:我需要如何重写我的方法以使其可测试?
【问题讨论】:
-
您是否尝试过调试测试以查看代码是否通过预期路径?
-
任务正在运行,只是在另一个线程中,所以你无法验证它。
-
@KerriBrown 它确实超过了这条线,我对其进行了调试,但起订量没有检测到它已通过。 Moq 说它从未被调用过。
-
因为它从未在调用验证的线程上调用过。
-
@user2128702 你没有在 IDE 中收到关于任务在单独线程上执行的绿色波浪形警告吗?
标签: c# unit-testing mocking moq assert