2 * Copyright (c) 2010-2020 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.Assert.*;
16 import static org.mockito.Mockito.*;
18 import java.util.function.Consumer;
20 import org.junit.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 {
30 @SuppressWarnings("unused")
31 @Test(expected = IllegalArgumentException.class)
32 public void testConstructorWrongCacheTime() {
33 // Fail if cache time is <= 0
34 new ExpiringCacheAsync<>(0, () -> {
38 @SuppressWarnings("unused")
39 @Test(expected = IllegalArgumentException.class)
40 public void testConstructorNoRefrehCommand() {
41 new ExpiringCacheAsync<>(2000, null);
45 public void testFetchValue() {
46 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
47 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
48 assertTrue(t.isExpired());
50 @SuppressWarnings("unchecked")
51 Consumer<Double> consumer = mock(Consumer.class);
53 // We expect a call to the updater object
54 verify(u).requestCacheUpdate();
55 // Update the value now
57 // The value should be valid
58 assertFalse(t.isExpired());
59 // We expect a call to the consumer
60 ArgumentCaptor<Double> valueCaptor = ArgumentCaptor.forClass(Double.class);
61 verify(consumer).accept(valueCaptor.capture());
62 assertEquals(10.0, valueCaptor.getValue(), 0);
66 public void testExpiring() {
67 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
68 @SuppressWarnings("unchecked")
69 Consumer<Double> consumer = mock(Consumer.class);
71 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(100, u);
73 assertFalse(t.isExpired());
77 // There should be no call to update the cache
78 verify(u, times(0)).requestCacheUpdate();
82 } catch (InterruptedException ignored) {
85 // Request a value two times
88 // There should be one call to update the cache
89 verify(u, times(1)).requestCacheUpdate();
90 assertTrue(t.isExpired());
94 public void testFetchExpiredValue() {
95 ExpiringCacheUpdate u = mock(ExpiringCacheUpdate.class);
96 ExpiringCacheAsync<Double> t = new ExpiringCacheAsync<>(2000, u);
98 // We should always be able to get the raw value, expired or not
99 assertEquals(10.0, t.getExpiredValue(), 0);
101 assertTrue(t.isExpired());
102 assertEquals(10.0, t.getExpiredValue(), 0);