98 lines
3.0 KiB
C#
98 lines
3.0 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using Cysharp.Threading.Tasks;
|
|
using NUnit.Framework;
|
|
using ShrinkContext;
|
|
using ShrinkEventBus;
|
|
using UnityEngine;
|
|
|
|
namespace ShrinkContext.EventBusAdapter.Tests
|
|
{
|
|
public sealed class PingEvent : EventBase
|
|
{
|
|
public int Value { get; set; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// EventBus 订阅/注册即效应:组件停用时自动退订,无需手写卸载路径。
|
|
/// </summary>
|
|
public class EventBusEffectTests
|
|
{
|
|
private ShrinkContextRuntime _runtime = null!;
|
|
private ShrinkCtx _ctx = null!;
|
|
|
|
[SetUp]
|
|
public void SetUp()
|
|
{
|
|
_runtime = new ShrinkContextRuntime();
|
|
_ctx = _runtime.RootContext;
|
|
}
|
|
|
|
[TearDown]
|
|
public void TearDown()
|
|
{
|
|
_runtime.ShutdownAsync().GetAwaiter().GetResult();
|
|
EventBus.UnregisterAllEvents();
|
|
}
|
|
|
|
[Test]
|
|
public void EffectSubscribe_ReceivesEvents_AndAutoUnsubscribesOnContextDispose()
|
|
{
|
|
var received = new List<int>();
|
|
_ctx.EffectSubscribe<PingEvent>(e => received.Add(e.Value));
|
|
|
|
EventBus.TriggerEvent(new PingEvent { Value = 1 });
|
|
EventBus.TriggerEvent(new PingEvent { Value = 2 });
|
|
CollectionAssert.AreEqual(new[] { 1, 2 }, received);
|
|
|
|
_ctx.DisposeAsync().GetAwaiter().GetResult();
|
|
|
|
EventBus.TriggerEvent(new PingEvent { Value = 3 });
|
|
CollectionAssert.AreEqual(new[] { 1, 2 }, received,
|
|
"上下文回滚后订阅必须自动退订(IShrinkEventSubscription.Dispose 即逆操作)");
|
|
}
|
|
|
|
[Test]
|
|
public void EffectSubscribe_ManualDispose_OnlyUnsubscribesOwn()
|
|
{
|
|
var first = new List<int>();
|
|
var second = new List<int>();
|
|
_ctx.EffectSubscribe<PingEvent>(e => first.Add(e.Value));
|
|
var handle = _ctx.EffectSubscribe<PingEvent>(e => second.Add(e.Value));
|
|
|
|
handle.DisposeAsync().GetAwaiter().GetResult();
|
|
|
|
EventBus.TriggerEvent(new PingEvent { Value = 7 });
|
|
CollectionAssert.AreEqual(new[] { 7 }, first, "手动退订只影响自己的订阅");
|
|
Assert.IsEmpty(second);
|
|
}
|
|
|
|
[Test]
|
|
public void EffectRegister_ObjectSubscribers_AutoUnregisterOnContextDispose()
|
|
{
|
|
var subscriber = new InstanceSubscriber();
|
|
_ctx.EffectRegister(subscriber);
|
|
|
|
EventBus.TriggerEvent(new PingEvent { Value = 5 });
|
|
Assert.AreEqual(5, subscriber.LastValue);
|
|
|
|
_ctx.DisposeAsync().GetAwaiter().GetResult();
|
|
|
|
EventBus.TriggerEvent(new PingEvent { Value = 6 });
|
|
Assert.AreEqual(5, subscriber.LastValue, "实例注册随上下文回滚自动注销");
|
|
}
|
|
|
|
private sealed class InstanceSubscriber
|
|
{
|
|
public int LastValue { get; private set; }
|
|
|
|
[EventSubscribe]
|
|
public void OnPing(PingEvent e)
|
|
{
|
|
LastValue = e.Value;
|
|
}
|
|
}
|
|
}
|
|
}
|