Index of every page on this site: llms.txt
All skills
github avatar

/spring-boot-testing

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

Expert Spring Boot testing specialist that selects the best testing techniques for your situation: test slices, Testcontainers with @ServiceConnection, Failsafe integration tests, MockitoBean, JUnit and AssertJ. Written for Spring Boot 4 with notes for Boot 3.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/spring-boot-testing

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesdatajpatest.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

@DataJpaTest

Testing JPA repositories with isolated data layer slice.

Basic Structure

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {
  
  @Container
  @ServiceConnection
  // Testcontainers 2.x: org.testcontainers.postgresql.PostgreSQLContainer (non-generic); 1.x: PostgreSQLContainer<?> in org.testcontainers.containers
  static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
  
  @Autowired
  private OrderRepository orderRepository;
  
  @Autowired
  private TestEntityManager entityManager;
}

What Gets Loaded

  • Repository beans
  • EntityManager / TestEntityManager
  • DataSource
  • Transaction manager
  • No web layer, no services, no controllers

Testing Custom Queries

@Test
void shouldFindOrdersByStatus() {
  // Given - Using var for cleaner code
  var pending = new Order("PENDING");
  var completed = new Order("COMPLETED");
  entityManager.persist(pending);
  entityManager.persist(completed);
  entityManager.flush();
  
  // When
  var pendingOrders = orderRepository.findByStatus("PENDING");
  
  // Then - Using sequenced collection methods
  assertThat(pendingOrders).hasSize(1);
  assertThat(pendingOrders.getFirst().getStatus()).isEqualTo("PENDING");
}

Testing Native Queries

@Test
void shouldExecuteNativeQuery() {
  entityManager.persist(new Order("PENDING", BigDecimal.valueOf(100)));
  entityManager.persist(new Order("PENDING", BigDecimal.valueOf(200)));
  entityManager.flush();
  
  var total = orderRepository.calculatePendingTotal();
  
  assertThat(total).isEqualTo(new BigDecimal("300.00"));
}

Testing Pagination

@Test
void shouldReturnPagedResults() {
  // Insert 20 orders using IntStream
  IntStream.range(0, 20).forEach(i -> {
    entityManager.persist(new Order("PENDING"));
  });
  entityManager.flush();
  
  var page = orderRepository.findByStatus("PENDING", PageRequest.of(0, 10));
  
  assertThat(page.getContent()).hasSize(10);
  assertThat(page.getTotalElements()).isEqualTo(20);
  assertThat(page.getContent().getFirst().getStatus()).isEqualTo("PENDING");
}

Testing Lazy Loading

@Test
void shouldLazyLoadOrderItems() {
  var order = new Order("PENDING");
  order.addItem(new OrderItem("Product", 2));
  entityManager.persist(order);
  entityManager.flush();
  entityManager.clear(); // Detach from persistence context
  
  var found = orderRepository.findById(order.getId());
  
  assertThat(found).isPresent();
  // This will trigger lazy loading
  assertThat(found.get().getItems()).hasSize(1);
  assertThat(found.get().getItems().getFirst().getProduct()).isEqualTo("Product");
}

Testing Cascading

@Test
void shouldCascadeDelete() {
  var order = new Order("PENDING");
  order.addItem(new OrderItem("Product", 2));
  entityManager.persist(order);
  entityManager.flush();
  
  orderRepository.delete(order);
  entityManager.flush();
  
  assertThat(entityManager.find(OrderItem.class, order.getItems().getFirst().getId()))
    .isNull();
}

Testing @Query Methods

@Query("SELECT o FROM Order o WHERE o.createdAt > :date AND o.status = :status")
List<Order> findRecentByStatus(@Param("date") LocalDateTime date, 
                               @Param("status") String status);

@Test
void shouldFindRecentOrders() {
  var old = new Order("PENDING");
  old.setCreatedAt(LocalDateTime.now().minusDays(10));
  var recent = new Order("PENDING");
  recent.setCreatedAt(LocalDateTime.now().minusHours(1));
  
  entityManager.persist(old);
  entityManager.persist(recent);
  entityManager.flush();
  
  var recentOrders = orderRepository.findRecentByStatus(
    LocalDateTime.now().minusDays(1), "PENDING");
  
  assertThat(recentOrders).hasSize(1);
  assertThat(recentOrders.getFirst().getId()).isEqualTo(recent.getId());
}

Using H2 vs Real Database

H2 (Default - Not Recommended for Production Parity)

@DataJpaTest // Uses embedded H2 by default
class OrderRepositoryH2Test {
  // Fast but may miss DB-specific issues
}

Testcontainers (Recommended)

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryPostgresTest {
  @Container
  @ServiceConnection
  static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
}

Transaction Behavior

Tests are @Transactional by default and roll back after each test.

@Test
@Rollback(false) // Don't roll back (rarely needed)
void shouldPersistData() {
  orderRepository.save(new Order("PENDING"));
  // Data will remain in database after test
}

Key Points

  1. Use TestEntityManager for setup data
  2. Always flush() after persist() to trigger SQL
  3. Clear() the entity manager to test lazy loading
  4. Use real database (Testcontainers) for accurate results
  5. Test both success and failure cases
  6. Leverage Java 25 var keyword for cleaner variable declarations
  7. Use sequenced collection methods (getFirst(), getLast(), reversed())

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts18d4 checks · Risk SAFE
  • Gen Agent Trust Hub18d

    This skill is a comprehensive educational resource for Spring Boot testing. It provides best practices and code templates for modern Java testing frameworks. No malicious patterns, vulnerabilities, or security risks were identified during the analysis.

  • Socket18d

    No alerts

  • Snyk18d

    Risk: LOW · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated last month
  • Testing
  • spring-boot
  • junit
  • assertj
  • mockmvc
  • testcontainers
  • java
  • mockito
  • integration-testing
  • webmvctest

README badge

README badge for github/awesome-copilot/spring-boot-testing

Guides Spring Boot 4 testing with test slices (@WebMvcTest, @DataJpaTest, @RestClientTest), modern assertion libraries (AssertJ, MockMvcTester), and practical patterns like Testcontainers for database integration and context caching for performance. Covers the test pyramid, complexity assessment, and 80% coverage goals.

Generated from the current SKILL.md.

Does this skill work with Spring Boot 3, or is it Spring Boot 4 only?
This skill is written for Spring Boot 4. It covers Spring Boot 4-specific features like RestTestClient, @MockitoBean, and MockMvcTester. Some patterns (like traditional MockMvc) have backward-compatible alternatives documented, but the primary guidance assumes Spring Boot 4.
What assertion library does this skill recommend?
AssertJ. The skill explicitly prefers AssertJ's fluent, readable assertion style over verbose matchers, and includes references for assertions on scalars, collections, and other data types.
Does this cover testing with real databases, or only mocks?
Both. The skill recommends Testcontainers for data layer tests (@DataJpaTest) to use real databases in tests, and includes references for PostgreSQL, MySQL, and other JDBC sources.
What's the recommended test coverage target?
80% as a practical balance between quality and effort. The skill prioritizes business-critical paths, complex algorithms, error handling, and integration points over achieving maximum coverage.
Does this skill help with test data generation?
Yes. It references Instancio for generating complex test objects with 3+ properties, reducing boilerplate in test setup.

Generated from the current SKILL.md. These answers refresh after source changes.