-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternTest.java
More file actions
77 lines (67 loc) · 2.41 KB
/
Copy pathPatternTest.java
File metadata and controls
77 lines (67 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.hanserwei.patterns.observer;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import org.junit.jupiter.api.Test;
/** 验证本模式的协作契约与边界行为. */
public final class PatternTest {
/** 去重订阅和取消订阅影响后续通知. */
@Test
void managesSubscriptions() {
PublicationHub hub = new PublicationHub();
InboxListener inbox = new InboxListener();
hub.subscribe(inbox);
hub.subscribe(inbox);
hub.publish("A");
hub.unsubscribe(inbox);
hub.publish("B");
assertEquals(List.of("A"), inbox.titles());
}
/** 回调内取消其他订阅,不改变当前事件的订阅快照. */
@Test
void dispatchesSnapshot() {
PublicationHub hub = new PublicationHub();
InboxListener inbox = new InboxListener();
hub.subscribe(new RemovingListener(hub, inbox));
hub.subscribe(inbox);
hub.publish("A");
hub.publish("B");
assertEquals(List.of("A"), inbox.titles());
}
/** 明确采用失败即中断语义,后续观察者不会收到本次事件. */
@Test
void propagatesListenerFailure() {
PublicationHub hub = new PublicationHub();
InboxListener inbox = new InboxListener();
hub.subscribe(new FailingListener());
hub.subscribe(inbox);
assertThrows(IllegalStateException.class, () -> hub.publish("A"));
assertTrue(inbox.titles().isEmpty());
}
/** 模拟在回调中变更订阅的观察者. */
private static final class RemovingListener implements PublicationListener {
/** 被操作的事件主题. */
private final PublicationHub hub;
/** 将要取消的观察者. */
private final PublicationListener target;
/** 保存主题和取消目标. */
private RemovingListener(PublicationHub hub, PublicationListener target) {
this.hub = hub;
this.target = target;
}
/** 当前事件中取消目标,只影响后续事件. */
@Override
public void onPublished(String title) {
hub.unsubscribe(target);
}
}
/** 模拟业务回调失败的观察者. */
private static final class FailingListener implements PublicationListener {
/** 抛出异常以验证同步传播策略. */
@Override
public void onPublished(String title) {
throw new IllegalStateException("Listener failed");
}
}
}