Files
FlowScope/My project/Assets/FlowScope/Tests/EditMode/Data/DataSerializationTests.cs
2026-05-18 11:58:49 +08:00

86 lines
2.5 KiB
C#

using System;
using FlowScope.Save;
using NUnit.Framework;
using R3;
namespace FlowScope.Tests.EditMode.Data
{
public sealed class DataSerializationTests
{
[Test]
public void Serialize_ReactiveProperty_WritesValueOnly()
{
var serializer = new JsonSaveSerializer();
var data = new PlayerData();
data.Gold.Value = 25;
var json = serializer.SerializeToString(data);
Assert.That(json, Does.Contain("\"Gold\":25"));
Assert.That(json, Does.Not.Contain("ReactiveProperty"));
Assert.That(json, Does.Not.Contain("CurrentValue"));
}
[Test]
public void Deserialize_ReactiveProperty_UpdatesExistingDataInstance()
{
var serializer = new JsonSaveSerializer();
var data = new PlayerData();
serializer.PopulateFromString("{\"Gold\":42,\"Level\":7}", data);
Assert.That(data.Gold.Value, Is.EqualTo(42));
Assert.That(data.Level.Value, Is.EqualTo(7));
}
[Test]
public void Serialize_ReactiveCollection_WritesJsonArray()
{
var serializer = new JsonSaveSerializer();
var data = new InventoryData();
data.ItemIds.Add(3);
data.ItemIds.Add(5);
var json = serializer.SerializeToString(data);
Assert.That(json, Does.Contain("\"ItemIds\":[3,5]"));
}
[Test]
public void Deserialize_ReactiveCollection_ReplacesCollectionContents()
{
var serializer = new JsonSaveSerializer();
var data = new InventoryData();
data.ItemIds.Add(99);
serializer.PopulateFromString("{\"ItemIds\":[1,2,3]}", data);
Assert.That(data.ItemIds, Is.EqualTo(new[] { 1, 2, 3 }));
}
[Test]
public void Populate_TypeMismatch_ThrowsWithFieldName()
{
var serializer = new JsonSaveSerializer();
var exception = Assert.Throws<InvalidOperationException>(
() => serializer.PopulateFromString("{\"Gold\":\"wrong\"}", new PlayerData()));
Assert.That(exception.Message, Does.Contain("Gold"));
}
private sealed class PlayerData
{
public ReactiveProperty<int> Gold { get; } = new(0);
public ReactiveProperty<int> Level { get; } = new(1);
}
private sealed class InventoryData
{
public ReactiveCollection<int> ItemIds { get; } = new();
}
}
}