Controller snippet:
public async Task<IHttpActionResult> MyMethod()
{
try
{
//Do Stuff....
}
catch(Exception e)
{
return HandleException(e);
}
}
HandleException Snippet ...
public static HttpResponseMessage HandleException(Exception e)
{
//Bunch of unrelated stuff...
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(e.Message)
};
}
单元测试代码段
public async Task Test_InternalServerError()
{
Mock<IBusinessObject> boMocked = new Mock<IBusinessObject>();
Exception mockedException = new Exception("This is a mocked exception");
boMocked.Setup(x => x.MyMethod()).ThrowsAsync(mockedException);
MyController controller = new MyController(boMocked.Object);
IHttpActionResult actionResult = await controller.MyMethod();
ExceptionResult contentResult = actionResult as ExceptionResult;
Assert.IsTrue(contentResult.Exception.Message == mockedException.Message);
}
对于上面的单元测试,我遇到的问题是contentResult总是以NULL返回。
动作结果是返回一个ResponseMessageResult类型的对象,其状态代码为500.看起来它不喜欢ExceptionResult的情况,但我发誓几个月前这对我有用。
任何建议表示赞赏。