public IDictionary Build(string content){尝试{var settings = new JsonSerializerSettings{// NullValueHandling = NullValueHandling。忽略,MissingMemberHandling = MissingMemberHandling.Ignore};var contentStudioResponse = JsonConvert.DeserializeObject>(内容,设置);
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>();
}
//Below is my solution which is not working.
[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));
}
具有this的通读。这一步一步地说明了如何测试是否引发了异常。
但是,根据您所写的内容,代码不会引发异常,因为此时您只记录了异常,然后返回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();
}
这样做,您的代码将引发一个异常,您可以捕获该异常并对其进行测试。