Created
January 13, 2016 02:23
-
-
Save tuphamphuong/382fbe87297a57d9d461 to your computer and use it in GitHub Desktop.
Unit test Guava cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.cache.*; | |
import org.junit.Test; | |
import java.util.HashMap; | |
import java.util.Map; | |
import static org.fest.assertions.Assertions.assertThat; | |
/** | |
* Created by Tu Pham Phuong - phamptu@gmail.com on 7/2/15. | |
*/ | |
public class TestGuavaCache { | |
@Test | |
public void whenCacheMiss_thenValueIsComputed() { | |
CacheLoader<String, String> loader = new CacheLoader<String, String>() { | |
@Override | |
public String load(String key) { | |
return key.toUpperCase(); | |
} | |
}; | |
LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader); | |
assertThat(0).isEqualTo((int) cache.size()); | |
assertThat("HELLO").isEqualTo(cache.getUnchecked("hello")); | |
assertThat(1).isEqualTo((int) cache.size()); | |
} | |
@Test | |
public void whenPreloadCache_thenUsePutAll() { | |
CacheLoader<String, String> loader = new CacheLoader<String, String>() { | |
@Override | |
public String load(String key) { | |
return key.toUpperCase(); | |
} | |
}; | |
LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader); | |
Map<String, String> map = new HashMap<String, String>(); | |
map.put("first", "FIRST"); | |
map.put("second", "SECOND"); | |
cache.putAll(map); | |
assertThat(2).isEqualTo((int) cache.size()); | |
} | |
@Test | |
public void whenEntryRemovedFromCache_thenNotify() { | |
CacheLoader<String, String> loader = new CacheLoader<String, String>() { | |
@Override | |
public String load(final String key) { | |
return key.toUpperCase(); | |
} | |
}; | |
RemovalListener<String, String> listener = new RemovalListener<String, String>() { | |
@Override | |
public void onRemoval(RemovalNotification<String, String> n){ | |
if (n.wasEvicted()) { | |
String cause = n.getCause().name(); | |
assertThat(RemovalCause.SIZE.toString()).isEqualTo(cause); | |
} | |
} | |
}; | |
LoadingCache<String, String> cache = CacheBuilder.newBuilder() | |
.maximumSize(3) | |
.removalListener(listener) | |
.build(loader); | |
cache.getUnchecked("first"); | |
cache.getUnchecked("second"); | |
cache.getUnchecked("third"); | |
cache.getUnchecked("last"); | |
assertThat(3).isEqualTo((int) cache.size()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment