An in-memory repository
A repository is the part of a program that stores things, and a test of it needs a store that is fast, empty and disposable. A Map behind an interface gives exactly that: the tests call the interface, the implementation is one small class, and a database can replace it later without changing a test.
The interface
TaskStore.java is the contract: add a task, find it, remove it. The return types say what the caller can expect: Optional for a lookup that may miss, a boolean for a removal that may remove nothing.
import java.util.Optional;
interface TaskStore {
void add(String task);
Optional<String> find(String task);
boolean remove(String task);
}
The store behind a Map
InMemoryTaskStore.java keeps a LinkedHashMap. The map preserves insertion order, which makes a future listing deterministic without an extra sort. The duplicate check is part of the class, not of the map: the map would replace the old value silently, and the class chooses to reject it instead.
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
public class InMemoryTaskStore implements TaskStore {
private final Map<String, String> tasks = new LinkedHashMap<>();
@Override
public void add(String task) {
if (tasks.containsKey(task)) {
throw new IllegalStateException("duplicate: " + task);
}
tasks.put(task, task);
}
@Override
public Optional<String> find(String task) {
return Optional.ofNullable(tasks.get(task));
}
@Override
public boolean remove(String task) {
return tasks.remove(task) != null;
}
}
The tests
Each test starts from a new store, because the field is initialized in the declaration and the default lifecycle creates a new test instance for every method. The four tests cover the add, the miss, the removal and the duplicate.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Optional;
import org.junit.jupiter.api.Test;
public class InMemoryTaskStoreTest {
private final TaskStore store = new InMemoryTaskStore();
@Test
void findsAnAddedTask() {
store.add("write");
assertEquals(Optional.of("write"), store.find("write"));
}
@Test
void missingTaskIsEmpty() {
assertTrue(store.find("read").isEmpty());
}
@Test
void removesATask() {
store.add("write");
assertTrue(store.remove("write"));
assertTrue(store.find("write").isEmpty());
}
@Test
void rejectsADuplicate() {
store.add("write");
IllegalStateException error = assertThrows(
IllegalStateException.class,
() -> store.add("write"));
assertEquals("duplicate: write", error.getMessage());
}
}
The report
javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out TaskStore.java InMemoryTaskStore.java InMemoryTaskStoreTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ InMemoryTaskStoreTest ✔
│ ├─ rejectsADuplicate() ✔
│ ├─ findsAnAddedTask() ✔
│ ├─ removesATask() ✔
│ └─ missingTaskIsEmpty() ✔
└─ JUnit Vintage ✔
Test run finished after 931 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 4 tests found ]
[ 0 tests skipped ]
[ 4 tests started ]
[ 0 tests aborted ]
[ 4 tests successful ]
[ 0 tests failed ]
What the tests pin down
The four tests are a specification of the small contract: add makes the task findable, find returns empty for a miss, remove reports whether it removed, and a duplicate is an error rather than a silent overwrite. A future database store must pass the same four tests, which is why the tests call the interface and never the map.
A test that reached into the map with reflection would break when the store changes, without testing anything the caller can see. The public methods are the contract; the field is an implementation detail.
Exercises
- Add a test that removes a missing task and asserts the false result.
- Change the map to a HashMap and run. Do the tests still pass?
- Add a size method to the interface and a test for it, then implement it.
- Write a second implementation backed by a list and run the same tests against it. What must change in the test class?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why does the test call the interface rather than the Map field?
Answer
The interface is the contract the callers use, and it survives a storage change
The tests should describe what a caller sees; the map is an implementation detail.
-
What does
findreturn for a missing task?Answer
Optional.empty()
The Optional return type makes the miss explicit without a null to remember.
-
Why does
addthrow on a duplicate instead of replacing the value?Answer
The class chooses a rule that the map would not enforce by itself
A Map.put replaces silently, so the store adds the duplicate check it wants.
-
What does this program print?
public class Q1 { public static void main(String[] args) { java.util.Map<String, String> tasks = new java.util.HashMap<>(); tasks.put("write", "write"); System.out.println(tasks.get("write")); } }Answer
write
The key write maps to the value write.
-
What does this program print?
public class Q2 { public static void main(String[] args) { java.util.Map<String, String> tasks = new java.util.HashMap<>(); System.out.println(tasks.get("missing") == null); } }Answer
true
A HashMap returns null for a missing key, so the comparison is true.
-
What does this program print?
public class Q3 { public static void main(String[] args) { java.util.Optional<String> value = java.util.Optional.empty(); System.out.println(value.isEmpty()); } }Answer
true
An empty Optional returns true from isEmpty.
-
What does this program print?
public class Q4 { public static void main(String[] args) { java.util.Optional<String> value = java.util.Optional.of("write"); System.out.println(value.get()); } }Answer
write
get returns the value inside a non-empty Optional.
-
What does
removereturn when the task was not there?Answer
false
The boolean reports whether a value was removed, so a miss is false.
-
What does this program print?
public class Q5 { public static void main(String[] args) { java.util.Map<String, String> tasks = new java.util.LinkedHashMap<>(); tasks.put("b", "b"); tasks.put("a", "a"); System.out.println(tasks.keySet()); } }Answer
[b, a]
A LinkedHashMap keeps insertion order, so b comes before a.
-
Why is the field
private final Map?Answer
The store owns the map and nothing outside can replace or read it directly
Encapsulation keeps the storage an implementation detail; final means the reference never changes.
The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.
Article author: Arthur Isaev