test(serializer): 添加JSON序列化器单元测试并优化反序列化异常处理

- 添加了完整的JsonSerializer单元测试覆盖序列化和反序列化场景
- 优化了反序列化方法中的异常处理逻辑,改进错误信息
- 修改了DeserializeCore方法中未使用的参数命名
- 添加了对各种边界情况的测试验证,包括无效JSON和空值处理
This commit is contained in:
GeWuYou 2026-04-05 22:58:45 +08:00
parent 3d86cdb093
commit d2533de3be
2 changed files with 30 additions and 10 deletions

View File

@ -82,6 +82,23 @@ public sealed class JsonSerializerTests
});
}
[Test]
public void Deserialize_With_Runtime_Type_Should_Throw_With_Target_Type_Context_When_Json_Is_Invalid()
{
var serializer = new GameJsonSerializer();
var exception =
Assert.Throws<InvalidOperationException>(() =>
serializer.Deserialize("{invalid json}", typeof(PlayerStateStub)));
Assert.Multiple(() =>
{
Assert.That(exception, Is.Not.Null);
Assert.That(exception!.Message, Does.Contain(typeof(PlayerStateStub).FullName));
Assert.That(exception.InnerException, Is.Not.Null);
});
}
[Test]
public void Deserialize_With_Runtime_Type_Should_Return_Target_Runtime_Type()
{

View File

@ -67,7 +67,7 @@ public sealed class JsonSerializer
return (T)DeserializeCore(
data,
typeof(T),
static (json, type, settings) => JsonConvert.DeserializeObject<T>(json, settings));
static (json, _, settings) => JsonConvert.DeserializeObject<T>(json, settings));
}
/// <summary>
@ -94,22 +94,25 @@ public sealed class JsonSerializer
ArgumentNullException.ThrowIfNull(targetType);
ArgumentNullException.ThrowIfNull(deserialize);
object? result;
try
{
var result = deserialize(data, targetType, _settings);
if (result == null)
{
throw new InvalidOperationException(
$"Deserialization returned null for target type '{targetType.FullName}'.");
}
return result;
result = deserialize(data, targetType, _settings);
}
catch (Exception ex) when (ex is InvalidCastException)
catch (Exception ex) when (ex is not ArgumentException)
{
throw new InvalidOperationException(
$"Failed to deserialize JSON to target type '{targetType.FullName}'.",
ex);
}
if (result == null)
{
throw new InvalidOperationException(
$"Deserialization returned null for target type '{targetType.FullName}'.");
}
return result;
}
}