告诉我如何确保在检查异常时测试不落空ObjectNotFoundError
我模拟了一项服务,在设置中我尝试实现抛出异常的模拟
public async Task GetRequestWithNoSucccessNotFound()
{
var mockService = new Mock<ICompanyService>();
var mockLogger = new Mock<ILogger<CompaniesController>>();
mockService.Setup(service => service.GetCompany(It.IsAny<int>())).Throws<ObjectNotFoundException>();
var controller = new CompaniesController(mockLogger.Object, mockService.Object);
var result = await controller.Get(9999);
var viewResult = Assert.IsType<RequestResponseModel<CompanyViewModel>>(result);
Assert.False(result.IsSuccess);
}
服务方法如下所示
public async Task<CompanyViewModel> GetCompany(int companyId)
{
var company = await contextDb.Companies.AsNoTracking().Where(p => p.Id == companyId).SelectCompany().FirstOrDefaultAsync();
if (company == null)
{
throw new ObjectNotFoundException();
}
return company;
}
在这种情况下,测试失败并出现错误
System.NullReferenceException : Object reference not set to an instance of an object.
我怎样才能让假对象不放弃测试,但抛出一个在控制器中处理的异常?
UPD
得到
public async Task<RequestResponseModel<CompanyViewModel>> Get(int id)
{
try
{
var company = await CompanyService.GetCompany(id);
return RequestResponseModel<CompanyViewModel>.CreateSuccessObject(company);
}
catch (Exception e)
{
LogError(e);
this.SetErrorResponseStatusCode(e);
return RequestResponseModel<CompanyViewModel>.CreateRequestResponseErrorObject();
}
}
SetErrorResponseStatusCode
public static void SetErrorResponseStatusCode(this ControllerBase controller, Exception exception)
{
// set http status based on type of exception
if (exception is NotImplementedException)
{
controller.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
}
else if (exception is ObjectNotFoundException)
{
controller.Response.StatusCode = (int)HttpStatusCode.NotFound; // вот здесь падает
}
else
{
controller.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
}
我想指出,只有测试下降。访问 API 时,一切正常。
该属性
Response
等于null
,因为此时尚未设置它。您应该返回所需的
ActionResult
而不是作业StatusCode
。我删除了前缀
Set
,因为现在这个方法没有设置值,而是返回。相应地更改方法
Get
:应用模式匹配和表达式主体: