-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchain_of_responsibility_test.dart
100 lines (78 loc) · 2.31 KB
/
chain_of_responsibility_test.dart
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class Event {
final EventType type;
Event.click() : this(EventType.CLICK);
Event.move() : this(EventType.MOVE);
Event(this.type);
@override
String toString() => "${type}";
}
enum EventType { CLICK, MOVE }
abstract class EventHandler {
bool handle(Widget widget, Event event);
}
class _DoNothingEventHandler implements EventHandler {
@override
bool handle(Widget widget, Event event) => false;
}
final EventHandler doNothingEventHandler = _DoNothingEventHandler();
class Widget {
final String name;
final Widget? child;
final EventHandler handler;
Widget({
required this.name,
this.child,
EventHandler? handler,
}) : this.handler = handler ?? doNothingEventHandler;
/**
* Handles [event].
*
* Returns [true] if event was handled and [false] otherwise.
*/
bool handle(Event event) {
bool wasHandled = handler.handle(this, event);
return wasHandled || (child?.handle(event) ?? false);
}
@override
String toString() => "$runtimeType(name: $name)";
}
class MockEventHandler extends Mock implements EventHandler {}
void main() {
late Widget tree;
Event event = Event.move();
late EventHandler parentHandler;
late EventHandler childHandler;
setUp(() {
parentHandler = MockEventHandler();
childHandler = MockEventHandler();
tree = Widget(
name: "parent",
handler: parentHandler,
child: Widget(name: "child", handler: childHandler),
);
registerFallbackValue(tree);
registerFallbackValue(event);
});
test("should handle event by parent", () {
// given
when(() => parentHandler.handle(any(), any())).thenReturn(true);
when(() => childHandler.handle(any(), any())).thenReturn(true);
// when
tree.handle(event);
// then
verify(() => parentHandler.handle(any(), any())).called(equals(1));
verifyNoMoreInteractions(childHandler);
});
test("should pass event to child", () {
// given
when(() => parentHandler.handle(any(), any())).thenReturn(false);
when(() => childHandler.handle(any(), any())).thenReturn(true);
// when
tree.handle(event);
// then
verify(() => parentHandler.handle(any(), any())).called(equals(1));
verify(() => childHandler.handle(any(), any())).called(equals(1));
});
}