2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.network.internal.toberemoved.cache;
15 import static org.junit.jupiter.api.Assertions.*;
16 import static org.mockito.Mockito.*;
18 import java.util.function.Consumer;
20 import org.junit.jupiter.api.Test;
21 import org.mockito.ArgumentCaptor;
22 import org.openhab.binding.network.internal.toberemoved.cache.ExpiringCacheAsync.ExpiringCacheUpdate;
25 * Tests cases for {@see ExpiringAsyncCache}
27 * @author David Graeff - Initial contribution
29 public class ExpiringCacheAsyncTest {
31 public void testConstructorWrongCacheTime() {
32 assertThrows(IllegalArgumentException.class, () ->
33 // Fail if cache time is <= 0
34 new ExpiringCacheAsync<>(0, () -> {
39 public void testConstructorNoRefrehCommand() {
40 assertThrows(IllegalArgumentException.class, () -> new ExpiringCacheAsync<>(2000, null));
44 public void testFetchValue() {
45 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
46 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
47 assertTrue(t.isExpired());
49 @SuppressWarnings("unchecked")
50 Consumer<Double> consumer = mock(Consumer.class);
52 // We expect a call to the updater object
53 verify(u).requestCacheUpdate();
54 // Update the value now
56 // The value should be valid
57 assertFalse(t.isExpired());
58 // We expect a call to the consumer
59 ArgumentCaptor<Double> valueCaptor = ArgumentCaptor.forClass(Double.class);
60 verify(consumer).accept(valueCaptor.capture());
61 assertEquals(10.0, valueCaptor.getValue(), 0);
65 public void testExpiring() {
66 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
67 @SuppressWarnings("unchecked")
68 Consumer<Double> consumer = mock(Consumer.class);
70 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(100, u);
72 assertFalse(t.isExpired());
76 // There should be no call to update the cache
77 verify(u, times(0)).requestCacheUpdate();
81 } catch (InterruptedException ignored) {
84 // Request a value two times
87 // There should be one call to update the cache
88 verify(u, times(1)).requestCacheUpdate();
89 assertTrue(t.isExpired());
93 public void testFetchExpiredValue() {
94 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
95 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
97 // We should always be able to get the raw value, expired or not
98 assertEquals(10.0, t.getExpiredValue(), 0);
100 assertTrue(t.isExpired());
101 assertEquals(10.0, t.getExpiredValue(), 0);