2 * Copyright (c) 2010-2024 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.eclipse.jdt.annotation.NonNullByDefault;
21 import org.junit.jupiter.api.Test;
22 import org.mockito.ArgumentCaptor;
23 import org.openhab.binding.network.internal.toberemoved.cache.ExpiringCacheAsync.ExpiringCacheUpdate;
26 * Tests cases for {@see ExpiringAsyncCache}
28 * @author David Graeff - Initial contribution
31 public class ExpiringCacheAsyncTest {
33 public void testConstructorWrongCacheTime() {
34 assertThrows(IllegalArgumentException.class, () ->
35 // Fail if cache time is <= 0
36 new ExpiringCacheAsync<>(0, () -> {
41 public void testConstructorNoRefrehCommand() {
42 assertThrows(IllegalArgumentException.class, () -> new ExpiringCacheAsync<>(2000, null));
46 public void testFetchValue() {
47 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
48 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
49 assertTrue(t.isExpired());
51 @SuppressWarnings("unchecked")
52 Consumer<Double> consumer = mock(Consumer.class);
54 // We expect a call to the updater object
55 verify(u).requestCacheUpdate();
56 // Update the value now
58 // The value should be valid
59 assertFalse(t.isExpired());
60 // We expect a call to the consumer
61 ArgumentCaptor<Double> valueCaptor = ArgumentCaptor.forClass(Double.class);
62 verify(consumer).accept(valueCaptor.capture());
63 assertEquals(10.0, valueCaptor.getValue(), 0);
67 public void testExpiring() {
68 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
69 @SuppressWarnings("unchecked")
70 Consumer<Double> consumer = mock(Consumer.class);
72 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(100, u);
74 assertFalse(t.isExpired());
78 // There should be no call to update the cache
79 verify(u, times(0)).requestCacheUpdate();
83 } catch (InterruptedException ignored) {
86 // Request a value two times
89 // There should be one call to update the cache
90 verify(u, times(1)).requestCacheUpdate();
91 assertTrue(t.isExpired());
95 public void testFetchExpiredValue() {
96 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
97 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
99 // We should always be able to get the raw value, expired or not
100 assertEquals(10.0, t.getExpiredValue(), 0);
102 assertTrue(t.isExpired());
103 assertEquals(10.0, t.getExpiredValue(), 0);