Testing, Design Patterns and Basic System Design Questions
50 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)After the Spring and database questions, a backend round usually moves to three short topics: how you test your code, which design patterns you know, and how your app would cope with many more users. The interviewer checks that you answer each with one example from a project like ShopLite.
Unit vs integration tests, JUnit 5 and Mockito
A unit test checks one class with its dependencies replaced by mocks and runs in milliseconds. An integration test checks real parts together, such as a controller in Spring MVC or a repository on a database. An end-to-end test drives the whole system.
The test pyramid says: many unit tests, fewer integration tests, very few end-to-end tests. This JUnit 5 and Mockito test follows AAA: Arrange, Act, Assert.
Example 1 · A JUnit 5 + Mockito unit test for a service
Runs in: a Spring Boot project with spring-boot-starter-test (ShopLite, Section 18)
package com.shoplite.order;
import static org.assertj.core.api.Assertions.assertThat;import static org.assertj.core.api.Assertions.assertThatThrownBy;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;import static org.mockito.Mockito.when;
import java.math.BigDecimal;import java.util.Optional;
import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.InjectMocks;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;
/** A unit test: no Spring context, no database. The two dependencies are Mockito mocks. */@ExtendWith(MockitoExtension.class)class OrderServiceTest {
@Mock ProductRepository products; @Mock OrderRepository orders; @InjectMocks OrderService service;
@Test void placeOrder_chargesPriceTimesQuantity() { // Arrange when(products.findById(7L)).thenReturn(Optional.of(new Product(7L, "Head First Java", new BigDecimal("650.00"), 22))); when(orders.save(any(Order.class))).thenAnswer(call -> call.getArgument(0));
// Act Order order = service.placeOrder(7L, 2);
// Assert assertThat(order.total()).isEqualByComparingTo("1300.00"); verify(orders).save(any(Order.class)); }
@Test void placeOrder_unknownProduct_throwsAndSavesNothing() { when(products.findById(99L)).thenReturn(Optional.empty());
assertThatThrownBy(() -> service.placeOrder(99L, 1)) .isInstanceOf(ProductNotFoundException.class); verify(orders, never()).save(any()); }}$ mvn test -Dtest=OrderServiceTest ... [INFO] Running com.shoplite.order.OrderServiceTest [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.412 s -- in com.shoplite.order.OrderServiceTest [INFO] [INFO] Results: [INFO] [INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] BUILD SUCCESS
What this code does
- Arrange stubs the repository with
when(...).thenReturn(...), Act calls the service, and Assert checks the result and then the interaction withverify.verify(orders, never()).save(any())proves nothing was saved on failure. - No Spring context starts, so both tests run in well under a second. A
@WebMvcTestwould test the controller with@MockitoBeanfor this service.
Mockito creates mocks whose answers you program with when(...).thenReturn(...) and whose calls you check with verify(...). A stub only returns canned answers, a mock also records calls, and a fake is a small working version such as an in-memory repository. Spring slices: @WebMvcTest (controller and MockMvc), @DataJpaTest (repositories, rolled back after each test) and @SpringBootTest (the whole app). @MockitoBean replaces a bean inside a Spring test; Spring Boot 4 removed @MockBean.
Revise: Test pyramid (opens in a new tab), Mockito mocks and stubbing (opens in a new tab), Testing with MockMvc (opens in a new tab).
Predict the output
What does Mockito do?
Predict the result of each snippet.
Round 1 of 2
What happens when this test runs?
Singleton and Builder
A Singleton is a class with exactly one instance and a global access point. To make it thread-safe, use the holder idiom, an enum, or double-checked locking with a volatile field; a plain lazy null check can create two instances.
The follow-up is always "make it thread-safe". This example creates the instance from eight threads, then builds an immutable ticket with a Builder.
Example 2 · Thread-safe Singleton (holder and enum) and a Builder
import java.util.ArrayList;import java.util.List;
/** Thread-safe singleton, way 1: the holder idiom. The JVM initialises Holder once, on first use. */class AppConfig { private static int created = 0;
private AppConfig() { created++; }
private static class Holder { static final AppConfig INSTANCE = new AppConfig(); }
static AppConfig getInstance() { return Holder.INSTANCE; }
static int created() { return created; }}
/** Thread-safe singleton, way 2: an enum. Also safe against reflection and serialisation tricks. */enum IdGenerator { INSTANCE;
private long next = 1000;
synchronized long nextId() { return next++; }}
/** Builder: many optional fields, one readable call, an immutable result. */final class FestTicket { private final String event; private final String student; private final int seats; private final boolean foodCoupon;
private FestTicket(Builder b) { this.event = b.event; this.student = b.student; this.seats = b.seats; this.foodCoupon = b.foodCoupon; }
static Builder builder(String event, String student) { return new Builder(event, student); }
@Override public String toString() { return "FestTicket[event=" + event + ", student=" + student + ", seats=" + seats + ", foodCoupon=" + foodCoupon + "]"; }
static final class Builder { private final String event; private final String student; private int seats = 1; private boolean foodCoupon;
private Builder(String event, String student) { this.event = event; this.student = student; }
Builder seats(int seats) { if (seats < 1 || seats > 4) { throw new IllegalArgumentException("seats must be 1 to 4"); } this.seats = seats; return this; }
Builder foodCoupon(boolean foodCoupon) { this.foodCoupon = foodCoupon; return this; }
FestTicket build() { return new FestTicket(this); } }}
public class SingletonBuilderDemo {
public static void main(String[] args) throws InterruptedException { List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 8; i++) { Thread t = new Thread(AppConfig::getInstance); threads.add(t); t.start(); } for (Thread t : threads) { t.join(); } System.out.println("same object? " + (AppConfig.getInstance() == AppConfig.getInstance())); System.out.println("constructor ran " + AppConfig.created() + " time(s) for 8 threads");
System.out.println("ids: " + IdGenerator.INSTANCE.nextId() + ", " + IdGenerator.INSTANCE.nextId());
FestTicket ticket = FestTicket.builder("Techfest 2026", "Asha").seats(2).foodCoupon(true).build(); System.out.println(ticket); System.out.println(FestTicket.builder("Techfest 2026", "Ravi").build()); }}same object? true constructor ran 1 time(s) for 8 threads ids: 1000, 1001 FestTicket[event=Techfest 2026, student=Asha, seats=2, foodCoupon=true] FestTicket[event=Techfest 2026, student=Ravi, seats=1, foodCoupon=false]
What this code does
- Eight threads call
getInstance()at once, yet the constructor runs once: the JVM initialisesHolderexactly once, with nosynchronizedneeded. The enum gives the same guarantee and also survives serialisation. - The Builder takes the required fields up front, has defaults for the optional ones, validates in
seats, and returns an immutableFestTicket.
A Builder builds an object step by step through named methods and a final build(); use it when a constructor would need four or more parameters. StringBuilder, HttpClient.newBuilder() and Lombok @Builder are everyday Builders. Singleton downsides are global state and hard mocking, so in Spring you use a singleton-scoped bean instead.
Revise: Thread-safe singletons (opens in a new tab), Builder pattern (opens in a new tab).
Find the bug
Make the Singleton safe
One line in each class is the problem. Click it.
Two threads can each create a Config. Which line?
Round 1 of 2Strategy, Factory and Observer
Strategy puts interchangeable algorithms behind one interface, chosen at run time. Observer lets a subject notify many listeners without knowing what they do. A Factory creates the right object so the caller never names the concrete class.
A long if-else on a type is the sign of a missing Strategy. This checkout picks a discount through a factory and notifies listeners of the order.
Example 3 · Strategy, Factory and Observer in one checkout
import java.util.ArrayList;import java.util.List;import java.util.function.Consumer;
/** Strategy: one interface, interchangeable algorithms. */interface DiscountStrategy { int apply(int amount);}
class NoDiscount implements DiscountStrategy { public int apply(int amount) { return amount; }}
class StudentDiscount implements DiscountStrategy { public int apply(int amount) { return amount - amount * 10 / 100; // 10% off }}
class FestivalDiscount implements DiscountStrategy { public int apply(int amount) { return amount >= 1000 ? amount - 200 : amount; // flat 200 off on 1000 or more }}
/** Factory: callers ask by name and never use "new" on a concrete strategy. */class DiscountFactory { static DiscountStrategy forCode(String code) { return switch (code) { case "STUDENT" -> new StudentDiscount(); case "DIWALI" -> new FestivalDiscount(); default -> new NoDiscount(); }; }}
/** Observer: the checkout publishes an event; listeners subscribe without the checkout knowing them. */class Checkout { private final List<Consumer<String>> listeners = new ArrayList<>();
void subscribe(Consumer<String> listener) { listeners.add(listener); }
int pay(String student, int amount, String code) { int total = DiscountFactory.forCode(code).apply(amount); listeners.forEach(l -> l.accept(student + " paid Rs. " + total)); return total; }}
public class StrategyFactoryObserverDemo {
public static void main(String[] args) { Checkout checkout = new Checkout(); checkout.subscribe(event -> System.out.println(" SMS: " + event)); checkout.subscribe(event -> System.out.println(" Email: " + event));
for (String code : new String[] { "NONE", "STUDENT", "DIWALI" }) { System.out.println("Code " + code + ":"); checkout.pay("Asha", 1200, code); } }}Code NONE: SMS: Asha paid Rs. 1200 Email: Asha paid Rs. 1200 Code STUDENT: SMS: Asha paid Rs. 1080 Email: Asha paid Rs. 1080 Code DIWALI: SMS: Asha paid Rs. 1000 Email: Asha paid Rs. 1000
What this code does
- Each discount is a Strategy behind
DiscountStrategy;DiscountFactorypicks one by code, soCheckoutnever names a concrete class. A new coupon means a new class and one line in the factory. - The SMS and e-mail listeners are Observers:
Checkoutpublishes an event and does not know who listens. Spring's@EventListenerworks the same way.
Strategy replaces an if-else on a type and follows the open/closed principle; since Java 8 a strategy is often just a lambda. In the JDK, List.of and Calendar.getInstance are factories. Spring offers Observer through ApplicationEventPublisher and @EventListener.
Revise: Strategy pattern (opens in a new tab), Observer pattern (opens in a new tab), Simple factory and factory method (opens in a new tab).
Patterns inside Spring: proxy and templates
A Spring proxy is an object that stands in for your bean and adds work around each call, such as starting a transaction. @Transactional, @Cacheable and @Async work through a proxy, so a call from inside the same bean skips them.
Spring injects a proxy instead of your object. This example shows why a call inside the same class gets no transaction.
Example 4 · How a @Transactional proxy works, and why self-invocation skips it
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;
interface FeeService { void payFees(String student);
void payFeesTwice(String student);}
class RealFeeService implements FeeService { public void payFees(String student) { System.out.println(" saving payment for " + student); }
public void payFeesTwice(String student) { payFees(student); // "this.payFees": a plain call, the proxy never sees it payFees(student); }}
/** What Spring does for @Transactional, in miniature: wrap the bean in a proxy that adds work around each call. */public class TransactionalProxyDemo {
static FeeService transactionalProxy(FeeService target) { InvocationHandler handler = (proxy, method, args) -> { System.out.println(" BEGIN transaction (" + method.getName() + ")"); Object result = method.invoke(target, args); System.out.println(" COMMIT"); return result; }; return (FeeService) Proxy.newProxyInstance( FeeService.class.getClassLoader(), new Class<?>[] { FeeService.class }, handler); }
public static void main(String[] args) { FeeService service = transactionalProxy(new RealFeeService()); // what gets injected
System.out.println("Call through the proxy:"); service.payFees("Asha");
System.out.println("Self-invocation inside the bean:"); service.payFeesTwice("Ravi");
System.out.println("Injected class is a proxy? " + Proxy.isProxyClass(service.getClass())); }}Call through the proxy:
BEGIN transaction (payFees)
saving payment for Asha
COMMIT
Self-invocation inside the bean:
BEGIN transaction (payFeesTwice)
saving payment for Ravi
saving payment for Ravi
COMMIT
Injected class is a proxy? trueWhat this code does
- The injected object is a proxy (a JDK dynamic proxy here; Spring may also use a CGLIB subclass). Every call through it gets BEGIN and COMMIT around the real method.
- Inside
payFeesTwice, the twopayFeescalls go straight tothis, not through the proxy, so they get no transaction of their own. That is the self-invocation trap.
The Template Method pattern appears in JdbcTemplate and TransactionTemplate: Spring runs the fixed steps and you supply the part that changes. Other patterns: Front Controller (DispatcherServlet), Chain of Responsibility (the security filters), Observer (application events) and Factory (ApplicationContext).
Revise: Proxies behind @Transactional (opens in a new tab), Template classes (opens in a new tab).
Order of execution
A call through the proxy
Put the steps of a @Transactional call in order.
Load balancing and scaling
Vertical scaling gives one machine more CPU and memory. Horizontal scaling adds more machines behind a load balancer, which works best with stateless servers. The load balancer spreads requests and skips servers that fail health checks.
A load balancer hands requests to servers in turn, called round robin. This tiny model shows five requests over three servers.
import java.util.List;
public class RoundRobinDemo { public static void main(String[] args) { List<String> servers = List.of("app-1", "app-2", "app-3"); int next = 0; for (int request = 1; request <= 5; request++) { String server = servers.get(next); next = (next + 1) % servers.size(); System.out.println("request " + request + " -> " + server); } }}request 1 -> app-1 request 2 -> app-2 request 3 -> app-3 request 4 -> app-1 request 5 -> app-2
Another algorithm is least connections. Sticky sessions pin a user to one server because the session sits in that server's memory; stateless tokens or a shared session store avoid them, so servers can be added or removed freely.
Revise: Vertical vs horizontal scaling (opens in a new tab), Load balancer algorithms (opens in a new tab).
Predict the output
Skip the dead server
app-2 has failed its health check.
Which servers answer the next four requests?
Caching and scaling a database
Cache-aside means the app reads the cache first and, on a miss, reads the database and stores the result with a TTL. On a write it deletes the cached entry. LRU drops the least recently used entry when the cache is full.
The hard part of caching is staying correct after a write. This example keeps two products in an LRU cache and invalidates the entry on an update.
Example 5 · Cache-aside with an LRU cache and invalidation
import java.util.LinkedHashMap;import java.util.Map;
/** An LRU cache: a LinkedHashMap in access order that drops the least recently used entry when full. */class LruCache<K, V> extends LinkedHashMap<K, V> { private final int capacity;
LruCache(int capacity) { super(16, 0.75f, true); // true = access order, so get() moves an entry to the end this.capacity = capacity; }
@Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; }}
/** Cache-aside: read the cache first; on a miss, read the database and fill the cache. */class ProductService { private final Map<Integer, String> database = new LinkedHashMap<>(Map.of( 1, "Redmi Note 13 Rs. 17999", 2, "boAt Airdopes Rs. 1299", 3, "Clean Code Rs. 499")); private final LruCache<Integer, String> cache = new LruCache<>(2); int databaseReads = 0;
String find(int id) { String cached = cache.get(id); if (cached != null) { return "HIT " + cached; } databaseReads++; String fromDb = database.get(id); cache.put(id, fromDb); return "MISS " + fromDb; }
void updatePrice(int id, String newValue) { database.put(id, newValue); cache.remove(id); // invalidate, so the next read is fresh }
String cachedIds() { return cache.keySet().toString(); }}
public class CacheAsideDemo {
public static void main(String[] args) { ProductService service = new ProductService(); int[] reads = { 1, 1, 2, 3, 1 }; for (int id : reads) { System.out.println("product " + id + ": " + service.find(id) + " cache " + service.cachedIds()); } service.updatePrice(3, "Clean Code Rs. 449"); System.out.println("after price update: " + service.find(3)); System.out.println("database reads: " + service.databaseReads + " of " + (reads.length + 1)); }}product 1: MISS Redmi Note 13 Rs. 17999 cache [1] product 1: HIT Redmi Note 13 Rs. 17999 cache [1] product 2: MISS boAt Airdopes Rs. 1299 cache [1, 2] product 3: MISS Clean Code Rs. 499 cache [2, 3] product 1: MISS Redmi Note 13 Rs. 17999 cache [3, 1] after price update: MISS Clean Code Rs. 449 database reads: 5 of 6
What this code does
- The cache holds two products. Reading product 3 evicts product 2, the least recently used, so the next read of product 1 is a miss again.
- Updating the price deletes the cached copy, so the next read fetches the new price instead of a stale one. Real apps use Redis with a TTL, or Spring's
@Cacheableand@CacheEvict.
Scale a slow database in this order: fix queries and indexes (EXPLAIN), pool connections (HikariCP), cache hot reads, add read replicas, and only then shard (split rows across databases by a key). Replicas lag slightly, so read your own fresh writes from the primary. CAP: during a network partition a distributed store chooses consistency or availability.
Revise: Cache-aside and write-through (opens in a new tab), Replication and read replicas (opens in a new tab).
Order of execution
Cache-aside, step by step
Put the steps of a cached read in order.
Design a URL shortener at fresher level
Interviewers want a clear structure, not a perfect architecture. This example shows the core: Base62 short codes and a redirect lookup.
Example 6 · The core of a URL shortener: Base62 codes and a redirect
import java.util.HashMap;import java.util.Map;
/** Fresher-level URL shortener core: a database id turned into a short Base62 code. */class UrlShortener { private static final String ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final Map<String, String> codeToUrl = new HashMap<>(); // stands in for a table: id, code, long_url private long nextId;
UrlShortener(long firstId) { this.nextId = firstId; }
static String base62(long id) { if (id == 0) { return "0"; } StringBuilder code = new StringBuilder(); while (id > 0) { code.append(ALPHABET.charAt((int) (id % 62))); id /= 62; } return code.reverse().toString(); }
String shorten(String longUrl) { String code = base62(nextId++); // unique because the id is unique codeToUrl.put(code, longUrl); return code; }
String redirect(String code) { String url = codeToUrl.get(code); return url == null ? "404 Not Found" : "302 Found, Location: " + url; }}
public class UrlShortenerDemo {
public static void main(String[] args) { UrlShortener shortener = new UrlShortener(125_000_000L); String a = shortener.shorten("https://college.example.edu/fest/2026/registration?team=coders"); String b = shortener.shorten("https://college.example.edu/placements/drive/42/results"); System.out.println("short codes: " + a + ", " + b); System.out.println("GET /" + a + " -> " + shortener.redirect(a)); System.out.println("GET /zzzzzz -> " + shortener.redirect("zzzzzz")); System.out.println("6 characters give 62^6 = " + (long) Math.pow(62, 6) + " codes"); }}short codes: 8sud2, 8sud3 GET /8sud2 -> 302 Found, Location: https://college.example.edu/fest/2026/registration?team=coders GET /zzzzzz -> 404 Not Found 6 characters give 62^6 = 56800235584 codes
What this code does
- Each new link gets the next database id, and Base62 (digits, lowercase, uppercase) turns it into a short code, so codes never collide. Id 125000000 needs only five characters.
- A redirect is a lookup: found gives
302with aLocationheader, missing gives404. In the real design the map is a table plus a Redis cache.
Walk through it in six steps:
- Requirements: shorten a long URL and redirect a short one; reads far outnumber writes, say 100 to 1.
- Estimate: 1 million new links a day is about 12 writes per second, so about 1,200 redirects per second.
- API:
POST /api/urlsreturns201and the code;GET /{code}returns302with aLocationheader. - Data:
urls(id BIGINT PRIMARY KEY, code VARCHAR(10) UNIQUE, long_url TEXT, created_at). - Short code: Base62 of the auto-increment id (unique and short), or a random 7-character code with a uniqueness check.
- Scale: cache hot codes in Redis, stateless servers behind a load balancer, read replicas.
End with trade-offs: sequential ids make codes guessable, so use random codes if that matters; browsers cache a 301, so choose 302 when you need to count clicks. Revise: Design a URL shortener (opens in a new tab).
Order of execution
Structure the design answer
Put the parts of a system design answer in a good order.
Next step
Check your understanding
12 quick questions