Skip to lesson

Unit testing services without Spring

ShopLite works, but any change might break a rule such as "no duplicate SKU". Waiting seconds for Spring and MySQL to start before every check makes people skip tests. Can a rule be tested in milliseconds?

Constructor injection makes a service a plain object

Constructor injection means a class receives its dependencies as constructor parameters. Spring calls that constructor when it builds the bean, and a test can call the same constructor with new.

Here is ProductService's constructor, and then the same constructor called with new in a test. Spring is not needed to build the object.

Java
// src/main/java/com/shoplite/product/ProductService.java (part)ProductService(ProductRepository repository, CategoryService categoryService, ShopLiteProperties properties) {    this.repository = repository;    this.categoryService = categoryService;    this.lowStockThreshold = properties.lowStockThreshold();}
// In a test, the same constructor, no Spring:ProductService service = new ProductService(repository, categoryService, properties);

ShopLite's ProductService needs three things: a ProductRepository, the CategoryService and the ShopLiteProperties. The constructor is package-private, so a test in the package com.shoplite.product can call it. Nothing else in the class needs Spring to work.

Compare field injection (@Autowired on a private field). Only a framework can fill that field, so new gives an object with a null dependency. Example 1 builds a cut-down ProductService with a hand-written fake store and tests it with plain Java.

Example 1 · A hand-written fake repository: no Spring needed

FakeRepositoryDemo.javaJava
import java.math.BigDecimal;import java.util.HashMap;import java.util.Map;import java.util.Optional;
record Product(int id, String sku, String name, BigDecimal price, int stock) {}
/** What the service needs from storage: a cut-down version of ShopLite's ProductRepository. */interface ProductStore {    Optional<Product> findBySku(String sku);
    Product save(Product product);}
/** A hand-written fake: a HashMap instead of MySQL. It also counts how often save was called. */class InMemoryProductStore implements ProductStore {    private final Map<String, Product> bySku = new HashMap<>();    private int nextId = 16;    int saveCalls = 0;
    @Override    public Optional<Product> findBySku(String sku) {        return Optional.ofNullable(bySku.get(sku));    }
    @Override    public Product save(Product product) {        saveCalls++;        Product saved = new Product(nextId++, product.sku(), product.name(), product.price(), product.stock());        bySku.put(saved.sku(), saved);        return saved;    }}
class AlreadyExistsException extends RuntimeException {    AlreadyExistsException(String message) {        super(message);    }}
/** A cut-down ProductService: its only dependency arrives through the constructor. */class ProductService {    private final ProductStore store;
    ProductService(ProductStore store) {        this.store = store;    }
    Product create(String sku, String name, String price, int stock) {        store.findBySku(sku).ifPresent(existing -> {            throw new AlreadyExistsException("A product with SKU " + sku + " already exists.");        });        return store.save(new Product(0, sku, name, new BigDecimal(price), stock));    }}
public class FakeRepositoryDemo {    static int passed = 0;    static int failed = 0;
    static void check(String name, Object expected, Object actual) {        if (expected.equals(actual)) {            passed++;            System.out.println("PASS " + name);        } else {            failed++;            System.out.println("FAIL " + name + ": expected " + expected + " but was " + actual);        }    }
    public static void main(String[] args) {        // Arrange: a fake store and the service, created with plain "new". No Spring anywhere.        InMemoryProductStore store = new InMemoryProductStore();        ProductService service = new ProductService(store);
        // Test 1: a new SKU is saved and gets the next id        Product saved = service.create("ACC-KB100", "Zebronics Wireless Keyboard", "999.00", 30);        check("new product gets id 16", 16, saved.id());        check("save called once", 1, store.saveCalls);
        // Test 2: the same SKU again is rejected, and save is not called a second time        String message = "no exception";        try {            service.create("ACC-KB100", "Keyboard copy", "899.00", 5);        } catch (AlreadyExistsException e) {            message = e.getMessage();        }        check("duplicate SKU is rejected", "A product with SKU ACC-KB100 already exists.", message);        check("save still called once", 1, store.saveCalls);
        System.out.println(passed + " passed, " + failed + " failed");    }}
Output
PASS new product gets id 16
PASS save called once
PASS duplicate SKU is rejected
PASS save still called once
4 passed, 0 failed

What this code does

  • ProductService gets its ProductStore through the constructor, so new ProductService(store) is a complete, working object.
  • InMemoryProductStore is a fake: a working store on a HashMap that also counts save calls, so the test can prove the duplicate was never saved.
  • The two checks are what a JUnit test would assert. Mockito saves you writing the fake by hand, as the next example shows.

Find the bug

Why is this hard to test?

Click the line that makes a plain unit test difficult.

A test does new FeeService().fee() and gets a NullPointerException. Which line is the cause?

Round 1 of 2

ProductService with Mockito and no application context

A mock is a Mockito stand-in for a dependency. You script its answers with given(...) and later check which calls it received with verify(...), so the test needs no real database.

Test ProductService with a mock of its repository: arrange what the repository returns, call one method, check the result. The test class below has no Spring annotation at all.

Two test setups for the ProductService rule "a duplicate SKU is rejected". In a unit test the real ProductService is built with new and given a mock ProductRepository, so there is no Spring and no database, and it runs in milliseconds. In the real app the service uses a real repository and MySQL.

Example 2 · src/test/java/com/shoplite/product/ProductServiceTest.java

Runs in: the shoplite-api Spring Boot project

Java
package com.shoplite.product;
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.BDDMockito.given;import static org.mockito.Mockito.never;import static org.mockito.Mockito.verify;
import java.math.BigDecimal;import java.time.ZoneId;import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.junit.jupiter.api.extension.ExtendWith;import org.mockito.Mock;import org.mockito.junit.jupiter.MockitoExtension;import org.springframework.test.util.ReflectionTestUtils;
import com.shoplite.category.Category;import com.shoplite.category.CategoryService;import com.shoplite.common.AlreadyExistsException;import com.shoplite.common.OutOfStockException;import com.shoplite.common.ResourceInUseException;import com.shoplite.common.ResourceNotFoundException;import com.shoplite.common.ShopLiteProperties;
/** ProductService's rules on a plain object: no Spring context, no database, no HTTP. */@ExtendWith(MockitoExtension.class)class ProductServiceTest {
    @Mock    private ProductRepository repository;
    @Mock    private CategoryService categoryService;
    private ProductService service;
    @BeforeEach    void createService() {        ShopLiteProperties properties = new ShopLiteProperties(ZoneId.of("Asia/Kolkata"), 5);        service = new ProductService(repository, categoryService, properties);   // plain "new"    }
    @Test    void missingProductIsNotFound() {        given(repository.findById(99)).willReturn(Optional.empty());
        assertThatThrownBy(() -> service.get(99))                .isInstanceOf(ResourceNotFoundException.class)                .hasMessage("Product 99 was not found.");    }
    @Test    void duplicateSkuIsRejectedAndNothingIsSaved() {        Category accessories = new Category("Accessories", null);        given(categoryService.require(4)).willReturn(accessories);        given(repository.findBySku("ACC-AD141")).willReturn(Optional.of(product(6, "ACC-AD141", "boAt Airdopes 141", 120)));
        CreateProductRequest request = new CreateProductRequest("ACC-AD141", "Airdopes copy", 4,                new BigDecimal("999.00"), 10, true);
        assertThatThrownBy(() -> service.create(request))                .isInstanceOf(AlreadyExistsException.class)                .hasMessage("A product with SKU ACC-AD141 already exists.");        verify(repository, never()).save(any());    }
    @Test    void orderedProductCannotBeDeleted() {        given(repository.findById(1)).willReturn(Optional.of(product(1, "MOB-RN13", "Redmi Note 13 5G", 40)));        given(repository.isOrdered(1)).willReturn(true);
        assertThatThrownBy(() -> service.delete(1))                .isInstanceOf(ResourceInUseException.class)                .hasMessageContaining("appears in orders");        verify(repository, never()).delete(any());    }
    @Test    void takeStockFailsWhenTheUpdateChangesNoRow() {        Product iphone = product(3, "MOB-IP15", "iPhone 15 128GB", 8);        given(repository.takeStock(3, 9)).willReturn(0);          // the atomic UPDATE found too little stock
        assertThatThrownBy(() -> service.takeStock(iphone, 9))                .isInstanceOf(OutOfStockException.class)                .hasMessage("Only 8 units of iPhone 15 128GB are in stock; 9 were requested.");        assertThat(iphone.getStock()).isEqualTo(8);    }
    /** MySQL generates ids; in a unit test there is no database, so the test sets the id itself. */    private static Product product(int id, String sku, String name, int stock) {        Product product = new Product(sku, name, new Category("Mobiles", null), new BigDecimal("17999.00"), stock);        ReflectionTestUtils.setField(product, "id", id);        return product;    }}
Sample output
$ ./mvnw test -Dtest=ProductServiceTest
...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.shoplite.product.ProductServiceTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.874 s -- in com.shoplite.product.ProductServiceTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

What this code does

  • The test sits in the package com.shoplite.product, so it can call the package-private constructor and mock the package-private ProductRepository.
  • ReflectionTestUtils.setField (from spring-test, but no context) sets the id that MySQL would normally generate. checkSkuIsFree compares ids, so the product needs one.
  • Four rules in under a second: 404 message, duplicate SKU with no save, in-use delete, and the out-of-stock message with the real numbers.

@ExtendWith(MockitoExtension.class) lets Mockito create the @Mock fields before each test. The test then calls new ProductService(...) with those mocks and a real ShopLiteProperties record. given(...).willReturn(...) (from BDDMockito) is the same as when(...).thenReturn(...).

verify(repository, never()).save(any()) proves a rejected request saved nothing.

There is no @SpringBootTest, @Autowired or @MockitoBean in this test. If you see them in a test of pure rules, the test is slower than it needs to be.

Speed: milliseconds instead of seconds

An application context is Spring's container of beans, built at startup: every bean, the database pool, Hibernate and the web server. A unit test of a service needs none of it.

Compare the time of plain-object tests with the time of a Spring context start. Example 3 simulates the context start with a fixed pause.

Example 3 · Timing: plain-object tests vs a context start

TestSpeedDemo.javaJava
import java.util.HashMap;import java.util.Map;
/** A small rule to test: the price after a coupon, never below 1 rupee (amounts in paise, so no double). */class CouponRule {    long priceAfter(long pricePaise, long couponPaise) {        return Math.max(100, pricePaise - couponPaise);    }}
/** Stands in for an application context: many beans to build before the first test can run. */class SimulatedContext {    final Map<String, Object> beans = new HashMap<>();
    SimulatedContext() throws InterruptedException {        for (int i = 0; i < 300; i++) {            beans.put("bean" + i, new Object());        }        Thread.sleep(1500);   // scanning, auto-configuration, the connection pool, Flyway, Hibernate ...    }}
public class TestSpeedDemo {    public static void main(String[] args) throws InterruptedException {        long start = System.nanoTime();        int passed = 0;        for (int i = 0; i < 1000; i++) {            CouponRule rule = new CouponRule();              // a fresh plain object for every test            if (rule.priceAfter(49_900, 10_000) == 39_900) {                passed++;            }        }        long plainMs = (System.nanoTime() - start) / 1_000_000;        System.out.println("1000 plain-object tests: " + plainMs + " ms (" + passed + " passed)");
        start = System.nanoTime();        SimulatedContext context = new SimulatedContext();        long contextMs = (System.nanoTime() - start) / 1_000_000;        System.out.println("One simulated context start: " + contextMs + " ms (" + context.beans.size() + " beans)");    }}
Sample output
1000 plain-object tests: 1 ms (1000 passed)
One simulated context start: 1525 ms (300 beans)

What this code does

  • A thousand plain-object tests usually finish in a few milliseconds; your numbers will differ.
  • SimulatedContext stands in for a Spring startup with a fixed 1.5 second pause. A real ShopLite context is usually slower, and it also needs MySQL for the full app.
  • Context caching (the @SpringBootTest lesson) pays this cost once per setup, not once per test, but plain tests stay the fastest feedback you have.

A plain-object test costs only the time of the method call. A Spring test first starts a context: it scans classes, runs auto-configuration, opens the connection pool, runs Flyway and starts Hibernate. On a laptop that is usually 3 to 10 seconds for ShopLite.

Spring caches a started context and reuses it for later test classes with the same setup, but the cost is still paid once per different setup, and a test that needs MySQL also needs MySQL running. In the real project, ProductServiceTest finishes in under a second.

What still needs Spring: wiring, JSON, SQL, security

A unit test proves the service's own rules. It cannot prove what Spring adds around the object. Example 4 shows a rule that a plain object ignores completely.

A pyramid of four kinds of ShopLite tests. The wide bottom is plain unit tests with Mockito: many, milliseconds each. Above them are slice tests, @WebMvcTest and @DataJpaTest: some, about a second each. At the top are few @SpringBootTest full-flow tests, which are the slowest.

Example 4 · Rules in proxies are ignored by a plain object

ProxyRuleDemo.javaJava
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.util.function.Supplier;
/** Our own small version of @PreAuthorize("hasRole('ADMIN')"). */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)@interface AdminOnly {}
interface CatalogService {    String deleteProduct(int id);
    String findProduct(int id);}
class SimpleCatalogService implements CatalogService {    @AdminOnly    @Override    public String deleteProduct(int id) {        return "product " + id + " deleted";    }
    @Override    public String findProduct(int id) {        return "product " + id + " found";    }}
class CurrentUser {    static String role = "CUSTOMER";}
public class ProxyRuleDemo {
    /** What Spring does for rule annotations: wrap the bean in a proxy that checks the rule first. */    static CatalogService secured(CatalogService target) {        InvocationHandler handler = (proxy, method, args) -> {            Method real = target.getClass().getMethod(method.getName(), method.getParameterTypes());            if (real.isAnnotationPresent(AdminOnly.class) && !CurrentUser.role.equals("ADMIN")) {                throw new SecurityException("Access Denied");            }            return method.invoke(target, args);        };        return (CatalogService) Proxy.newProxyInstance(CatalogService.class.getClassLoader(),                new Class<?>[] {CatalogService.class}, handler);    }
    static void call(String label, Supplier<String> action) {        try {            System.out.println(label + " -> " + action.get());        } catch (SecurityException e) {            System.out.println(label + " -> denied: " + e.getMessage());        }    }
    public static void main(String[] args) {        CatalogService plain = new SimpleCatalogService();   // what a unit test creates with "new"        CatalogService bean = secured(plain);                 // what the Spring container would hand out
        CurrentUser.role = "CUSTOMER";        call("plain object, customer, delete 6", () -> plain.deleteProduct(6));        call("proxy,        customer, find 6  ", () -> bean.findProduct(6));        call("proxy,        customer, delete 6", () -> bean.deleteProduct(6));
        CurrentUser.role = "ADMIN";        call("proxy,        admin,    delete 6", () -> bean.deleteProduct(6));    }}
Output
plain object, customer, delete 6 -> product 6 deleted
proxy,        customer, find 6   -> product 6 found
proxy,        customer, delete 6 -> denied: Access Denied
proxy,        admin,    delete 6 -> product 6 deleted

What this code does

  • @AdminOnly plays the role of @PreAuthorize("hasRole('ADMIN')"). On the plain object nothing reads it, so the customer deletes product 6.
  • secured(...) wraps the object in a java.lang.reflect.Proxy that checks the annotation first, like the proxy Spring puts around a bean.
  • So a unit test of ProductService.delete cannot prove the admin rule. That needs a Spring test with method security, such as Section 17's ProductServiceSecurityTest.

Use a Spring test for these:

  • Wiring: every bean can be created and injected. One @SpringBootTest smoke test catches a missing bean.
  • HTTP and JSON: URLs, status codes, validation, ProblemDetail bodies. Use @WebMvcTest (next lesson).
  • SQL: derived queries, @Query JPQL, Flyway migrations, constraints. Use @DataJpaTest.
  • Proxies: @PreAuthorize and @Transactional only work through the Spring proxy, so a plain object ignores them.

Predict the output

Which test proves it?

Pick the cheapest test that can prove each check.

Round 1 of 4

Which test fits?

// Check: a coupon never makes the price
// lower than Rs 1

Next step

Check your understanding

12 quick questions