1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.chabala.brick.controllab;
20
21 import org.junit.Rule;
22 import org.junit.Test;
23 import org.mockito.Mock;
24 import org.mockito.junit.MockitoJUnit;
25 import org.mockito.junit.MockitoRule;
26
27 import java.time.Duration;
28
29 import static org.mockito.Mockito.*;
30
31
32
33
34 public class KeepAliveMonitorTest {
35
36 private final Duration keepAliveDuration = Duration.ofMillis(500);
37 private final Duration nineTenthsDuration = keepAliveDuration.multipliedBy(9).dividedBy(10);
38 private final long keepAliveDurationMs = keepAliveDuration.toMillis();
39
40 @Rule
41 public MockitoRule rule = MockitoJUnit.rule();
42
43 @Mock
44 private SerialPortWriter serialPortWriter;
45
46 @Test
47 public void testMonitorSendsKeepAlives() throws Exception {
48 when(serialPortWriter.getPortName()).thenReturn("COM#");
49 try (KeepAliveMonitor monitor = new KeepAliveMonitor(serialPortWriter, nineTenthsDuration)) {
50 verify(serialPortWriter, after(keepAliveDurationMs).times(1)).sendCommand(anyByte(), any());
51 verify(serialPortWriter, after(keepAliveDurationMs).times(2)).sendCommand(anyByte(), any());
52 }
53 }
54
55 @Test
56 public void testResetPreventsKeepAlives() throws Exception {
57 long threeQuartersDurationMs = keepAliveDuration.multipliedBy(3).dividedBy(4).toMillis();
58 try (KeepAliveMonitor monitor = new KeepAliveMonitor(serialPortWriter, nineTenthsDuration)) {
59 verify(serialPortWriter, after(threeQuartersDurationMs).never()).sendCommand(anyByte(), any());
60 monitor.reset();
61 verify(serialPortWriter, after(threeQuartersDurationMs).never()).sendCommand(anyByte(), any());
62 verify(serialPortWriter, only()).getPortName();
63 }
64 }
65
66 @Test
67 public void testClosePreventsKeepAlives() throws Exception {
68 try (KeepAliveMonitor monitor = new KeepAliveMonitor(serialPortWriter, nineTenthsDuration)) {
69 monitor.close();
70 verify(serialPortWriter, after(keepAliveDuration.multipliedBy(2).toMillis()).only()).getPortName();
71 }
72 }
73 }