[英]How write Unit test in Catch block in Xunit?
在下面的函数中,我想测试使用 XUnit 抛出异常的情况。 测试应验证是否正确抛出了异常。
public IDictionary<string, Label> Build(string content)
{
try
{
var settings = new JsonSerializerSettings
{
MissingMemberHandling = MissingMemberHandling.Ignore
};
var contentStudioResponse = JsonConvert.DeserializeObject<ContentStudioResponse<CmsLabel>>(content, settings);
if (contentStudioResponse?.Items == null)
{
_logger.Warning("No records found in content studio response for label:({@content})", content);
return new Dictionary<string, Label>();
}
return contentStudioResponse.Items.ToDictionary(x => x.Key,
x => new Label
{
Value = x.DynamicProperties.MicroContentValue
}
);
}
catch (Exception e)
{
_logger.Error(e, "Failed to deserialize or build contentstudio response for label");
return new Dictionary<string, Label>();
}
}
以下是我不起作用的解决方案:
[Fact]
public void Builder_ThrowsException()
{
string json_responsive_labels = "abcd";
var builder = new LabelBuilder(_testLogger).Build(json_responsive_labels);
Assert.Throws<Exception>(() => builder);
//var sut = new LabelBuilder(_testLogger);
//Should.Throw<Exception>(() => sut.Build(json_responsive_labels));
}
有一个读通过的这个。 这一步一步解释了如何测试抛出的异常。
但是,根据您编写的内容,代码不会抛出异常,因为此时您只记录异常然后返回Dictionary
。
catch (Exception e)
{
_logger.Error(e, "Failed to deserialize or build contentstudio response for label");
return new Dictionary<string, Label>();
}
您真正想要做的是显式抛出异常,如下所示:
catch (Exception e)
{
throw new Exception();
}
这样做时,您的代码将抛出一个异常,您可以对其进行捕获和测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.