我有以下方法:
public async Task<SecurityRoleDeleteResult> DeleteSecurityRoleByRoleId(int securityRoleId)
{
string url = $"{_housingDataSecurityConfiguration.HousingDataSecurityWebApiUrl}SecurityRoles/Delete";
HttpResponseMessage message = _apiClientService.Post(url, securityRoleId);
if (message.StatusCode == HttpStatusCode.InternalServerError)
{
return SecurityRoleDeleteResult.ErrorOccurred;
}
int intResult = 0;
var apiResult = await message.Content.ReadAsStringAsync();
if (int.TryParse(apiResult, out intResult))
{
return (SecurityRoleDeleteResult)intResult;
}
else
{
return SecurityRoleDeleteResult.ErrorOccurred;
}
}
我现在正尝试为其编写单元测试,到目前为止:
[Test]
public async Task DeleteSecurityRoleByRoleId()
{
_mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
.Returns(new HttpResponseMessage {StatusCode = HttpStatusCode.OK});
SecurityRoleDeleteResult result = await _securityRoleService.DeleteSecurityRoleByRoleId(It.IsAny<int>());
Assert.AreEqual(SecurityRoleDeleteResult.Success, result);
}
这里的问题是,当我尝试在
_securityRoleService.DeleteSecurityRoleByRoleId
方法中运行测试时,我尝试设置var apiResult
message.content为null,因为在这种情况下,我只是在 mock ,因此崩溃。我怎样才能模拟出来,这样我的测试才能正常工作?
最佳答案
我知道了我的问题。与其删除我的问题,我还想将所做的更改发布到测试中。基本上我没有 mock 内容。
HttpContent content = new StringContent("4");
_mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
.Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = content });
因此,根据您可能希望返回的内容类型,可能需要更改内容的类型。
关于c# - 发出Moq'ing HttpResponseMessage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50523513/