[英]System.Text.Json / NUnit - Unit testing custom Json converter / Utf8JsonReader
I have a series of test methods to verify whether my custom Json converter (System.Text.Json) throws expected exceptions.我有一系列测试方法来验证我的自定义 Json 转换器 (System.Text.Json) 是否抛出预期的异常。 One of such method:其中一种方法:
[Test]
public void ReadJsonTokenNullThrows()
{
// Arrange
// Act & Assert
var exception = Assert.Throws<JsonException>(() =>
{
var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes("null"), false, new JsonReaderState(new JsonReaderOptions()));
utf8JsonReader.Read();
sut.Read(ref utf8JsonReader, typeof(DateTime), serializerOptions);
});
Assert.AreEqual("JSON value was a literal null", exception.Message);
}
I'd like to have only the line sut.Read(...);
我只想要行sut.Read(...);
inside the Assert.Throws..
code block, however when I move the Utf8JsonReader initialization and utf8JsonReader.Read() outside of it, I get the compiler error:在Assert.Throws..
代码块内,但是当我将 Utf8JsonReader 初始化和 utf8JsonReader.Read() 移到它之外时,出现编译器错误:
Cannot use ref local 'utf8JsonReader' inside an anonymous method, lambda expression, or query expression.
Is there a way around to do this?有没有办法做到这一点? Preferably without the try/catch最好没有 try/catch
Utf8JsonReader is a ref-struct and hence it cannot be passed to the lambda method. Utf8JsonReader 是一个引用结构,因此它不能传递给 lambda 方法。 See:看:
Assert.Throws<FormatException>(() =>
{
var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json), options);
while (reader.TokenType == JsonTokenType.None)
{
if (!reader.Read())
{
break;
}
}
_target.Read(ref reader, typeof(DateOnly), null);
});
where _target is a custom DateOnlyConverter其中 _target 是自定义 DateOnlyConverter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.