我有以下方法:
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,因为在这种情况下我只是嘲笑所以崩溃。
我如何模拟这个以便我的测试能够起作用?
答案 0 :(得分:7)
我想出了我的问题。而不是删除我的问题,我想我会将我的更改发布到测试中。基本上我没有嘲笑内容。
HttpContent content = new StringContent("4");
_mockApiClientService.Setup(a => a.Post(It.IsAny<string>(), It.IsAny<int>()))
.Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = content });
因此,根据您可能希望返回的内容类型,您可能需要更改内容类型。