package com.bookshop.structural.proxy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.bookshop.domain.Book;
import java.util.Optional;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("Proxy -- a caching stand-in for the slow remote catalog")
class CachingCatalogProxyTest {
private final RemoteBookCatalog remote = new RemoteBookCatalog();
private final BookCatalog catalog = new CachingCatalogProxy(remote);
@Test
@DisplayName("repeat lookups are served from cache -- one remote round-trip, not three")
void cachesRepeatLookups() {
catalog.findByIsbn("978-0134685991");
catalog.findByIsbn("978-0134685991");
Optional<Book> book = catalog.findByIsbn("978-0134685991");
assertEquals("Effective Java", book.orElseThrow().title());
assertEquals(1, remote.lookupCount());
}
@Test
@DisplayName("misses are cached too -- an unknown ISBN is only asked about once")
void cachesMisses() {
assertTrue(catalog.findByIsbn("no-such-isbn").isEmpty());
assertTrue(catalog.findByIsbn("no-such-isbn").isEmpty());
assertEquals(1, remote.lookupCount());
}
@Test
@DisplayName("proxy and real catalog are interchangeable -- clients hold the same interface")
void proxyIsTransparent() {
BookCatalog direct = remote;
BookCatalog proxied = catalog;
assertEquals(direct.findByIsbn("978-0201633610"), proxied.findByIsbn("978-0201633610"));
}
}