Real World Example

A Shared Test Setup for ShopEase

Teams at companies like Swiggy and Zomato run hundreds of repository tests on every pull request. The pattern: one container definition, one base class, test data builders, and checks for the rules that hurt most when broken.

@TestConfiguration(proxyBeanMethods = false)
public class PostgresTestConfig {
    @Bean
    @ServiceConnection
    PostgreSQLContainer<?> postgres() {
        return new PostgreSQLContainer<>("postgres:16-alpine").withReuse(true);
    }
}

@DataJpaTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true")
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(PostgresTestConfig.class)
public abstract class RepositoryTestBase {
    @Autowired protected TestEntityManager tem;
    @Autowired protected EntityManagerFactory emf;

    protected Statistics stats() { return emf.unwrap(SessionFactory.class).getStatistics(); }

    protected void flushAndClear() { tem.flush(); tem.clear(); stats().clear(); }
}

class ProductSoftDeleteTest extends RepositoryTestBase {
    @Autowired ProductRepository products;

    @Test
    void deletedProductsAreHiddenButKept() {
        Product p = tem.persist(TestData.product("Ceiling Fan"));
        flushAndClear();

        products.deleteById(p.getId());
        flushAndClear();

        assertThat(products.findAll()).isEmpty();
        Number raw = (Number) tem.getEntityManager()
                .createNativeQuery("select count(*) from products where id = :id")
                .setParameter("id", p.getId()).getSingleResult();
        assertThat(raw.intValue()).isEqualTo(1);       // row still there for invoices
    }
}

CI Output

Pipeline

./mvnw verify

Example output

[INFO] Running com.shopease.product.ProductSoftDeleteTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.84 s
[INFO] Running com.shopease.order.OrderQueryCountTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.51 s
[INFO] Running com.shopease.tenant.TenantIsolationTest
[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.37 s
[INFO] Results:
[INFO] Tests run: 61, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS