Skip to content

Commit

Permalink
test: add test
Browse files Browse the repository at this point in the history
  • Loading branch information
pipinet committed Dec 12, 2023
1 parent 7d99819 commit db99c09
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,10 @@

import com.google.common.base.Supplier;

import javax.annotation.CheckForNull;

public class RuntimeExpiringMemoizingSupplier<T> implements Supplier<T> {
private final Supplier<WithExpiring<T>> delegate;
@CheckForNull
private transient volatile T value;
private transient volatile long expirationNanos;
private T value;
private volatile long expirationNanos;

public RuntimeExpiringMemoizingSupplier(Supplier<WithExpiring<T>> delegate) {
this.delegate = delegate;
Expand All @@ -24,7 +21,7 @@ public T get() {
}
}
long now = System.nanoTime();
if (now > expirationNanos) {
if (now < expirationNanos) {
return this.value;
}
synchronized (this) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.qwlabs.lang;

import com.google.common.base.Supplier;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class RuntimeExpiringMemoizingSupplierTest {
@Test
void should_call_once(@Mock RealSupplier delegate) {
RuntimeExpiringMemoizingSupplier<String> supplier = new RuntimeExpiringMemoizingSupplier<>(delegate);

when(delegate.get()).thenReturn(WithExpiring.of("1", 1, TimeUnit.DAYS));

var value1 = supplier.get();
var value2 = supplier.get();

assertSame(value1, value2);
assertThat(value1, is("1"));

verify(delegate).get();
}

static class RealSupplier implements Supplier<WithExpiring<String>> {
@Override
public WithExpiring<String> get() {
return WithExpiring.of("real", 1, TimeUnit.DAYS);
}
}
}

0 comments on commit db99c09

Please sign in to comment.