Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.junit.Before;
- import org.junit.Test;
- import java.util.HashMap;
- import java.util.Map;
- import static org.hamcrest.MatcherAssert.assertThat;
- import static org.hamcrest.Matchers.is;
- import static org.hamcrest.Matchers.nullValue;
- public class HashMapTest {
- private Map<String, String> map1;
- @Before
- public void setUp() throws Exception {
- map1 = new HashMap<>();
- }
- @Test
- public void empty_after_init() {
- assertThat(map1.isEmpty(), is(true));
- }
- @Test
- public void compute() {
- map1.put("foo1", "bar1");
- map1.put("foo2", "bar2");
- map1.compute("foo1", (k, v) -> (v == null) ? "null value" : "not null value");
- assertThat(map1.get("foo1"), is("not null value"));
- }
- @Test
- public void computeIfAbsent() {
- map1.put("foo1", "bar1");
- map1.computeIfAbsent("foo2", k -> "null value");
- assertThat(map1.get("foo2"), is("null value"));
- assertThat(map1.size(), is(2));
- }
- @Test
- public void computeIfPresent() {
- map1.put("foo1", "bar1");
- map1.computeIfPresent("foo1", (k, v) -> "was " + v);
- assertThat(map1.get("foo1"), is("was bar1"));
- assertThat(map1.size(), is(1));
- map1.computeIfPresent("foo2", (k, v) -> "was " + v);
- assertThat(map1.size(), is(1));
- }
- @Test
- public void put_overwrite() {
- map1.put("foo1", "bar1");
- map1.put("foo1", "bar2");
- assertThat(map1.size(), is(1));
- assertThat(map1.get("foo1"), is("bar2"));
- }
- @Test
- public void putIfAbsent() {
- map1.put("foo1", "bar1");
- map1.putIfAbsent("foo1", "insert because of absence");
- map1.putIfAbsent("foo2", "insert becase of absence");
- assertThat(map1.size(), is(2));
- assertThat(map1.get("foo1"), is("bar1"));
- assertThat(map1.get("foo2"), is("insert becase of absence"));
- }
- @Test
- public void merge() {
- map1.put("foo1", "bar1");
- map1.merge("foo1", ": message", String::concat);
- map1.merge("foo2", ": message", String::concat);
- assertThat(map1.size(), is(2));
- assertThat(map1.get("foo1"), is("bar1: message"));
- assertThat(map1.get("foo2"), is(": message"));
- }
- @Test
- public void remove() {
- map1.put("foo1", "bar1");
- map1.remove("foo1", "bar2");
- assertThat(map1.size(), is(1));
- assertThat(map1.get("foo1"), is("bar1"));
- map1.remove("foo1");
- assertThat(map1.size(), is(0));
- assertThat(map1.get("foo1"), is(nullValue()));
- }
- @Test
- public void replace() {
- map1.replace("foo1", "bar1");
- assertThat(map1.size(), is(0));
- map1.put("key1", "bar1");
- map1.replace("key1", "value1");
- assertThat(map1.get("key1"), is("value1"));
- map1.replace("key1", "bar1", "newvalue");
- assertThat(map1.get("key1"), is("value1"));
- map1.replace("key1", "value1", "newvalue");
- assertThat(map1.get("key1"), is("newvalue"));
- }
- }
Add Comment
Please, Sign In to add comment