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.

referencesmockitobean.md

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

@MockitoBean

Mocking dependencies in Spring Boot tests (replaces deprecated @MockBean in Spring Boot 4+).

Overview

@MockitoBean replaces the deprecated @MockBean annotation in Spring Boot 4.0+. It creates a Mockito mock and registers it in the Spring context, replacing any existing bean of the same type.

Basic Usage

@WebMvcTest(OrderController.class)
class OrderControllerTest {
  
  @MockitoBean
  private OrderService orderService;
  
  @MockitoBean
  private UserService userService;
}

Supported Test Slices

  • @WebMvcTest - Mock service/repository dependencies
  • @WebFluxTest - Mock reactive service dependencies
  • @SpringBootTest - Replace real beans with mocks

Stubbing Methods

Basic Stub

@Test
void shouldReturnOrder() {
  Order order = new Order(1L, "PENDING");
  given(orderService.findById(1L)).willReturn(order);
  
  // Test code
}

Multiple Returns

given(orderService.findById(anyLong()))
  .willReturn(new Order(1L, "PENDING"))
  .willReturn(new Order(2L, "COMPLETED"));

Throwing Exceptions

given(orderService.findById(999L))
  .willThrow(new OrderNotFoundException(999L));

Argument Matching

given(orderService.create(argThat(req -> req.getQuantity() > 0)))
  .willReturn(1L);

given(orderService.findByStatus(eq("PENDING")))
  .willReturn(List.of(new Order()));

Verifying Interactions

Verify Method Called

verify(orderService).findById(1L);

Verify Never Called

verify(orderService, never()).delete(any());

Verify Count

verify(orderService, times(2)).findById(anyLong());
verify(orderService, atLeastOnce()).findByStatus(anyString());

Verify Order

InOrder inOrder = inOrder(orderService, userService);
inOrder.verify(orderService).findById(1L);
inOrder.verify(userService).getUser(any());

Resetting Mocks

Mocks are reset between tests automatically. To reset mid-test:

Mockito.reset(orderService);

@MockitoSpyBean for Partial Mocking

Use @MockitoSpyBean to wrap a real bean with Mockito.

@SpringBootTest
class OrderServiceIntegrationTest {
  
  @MockitoSpyBean
  private PaymentGatewayClient paymentClient;
  
  @Test
  void shouldProcessOrder() {
    doReturn(true).when(paymentClient).processPayment(any());
    
    // Test with real service but mocked payment client
  }
}

@TestBean for Custom Test Beans

Register a custom bean instance in the test context:

@SpringBootTest
class OrderServiceTest {
  
  @TestBean
  private PaymentGatewayClient paymentClient() {
    return new FakePaymentClient();
  }
}

Scoping: Singleton vs Prototype

Spring Framework 7+ (Spring Boot 4+) supports mocking non-singleton beans:

@Component
@Scope("prototype")
public class OrderProcessor {
  public String process() { return "real"; }
}

@SpringBootTest
class OrderServiceTest {
  @MockitoBean
  private OrderProcessor orderProcessor;
  
  @Test
  void shouldWorkWithPrototype() {
    given(orderProcessor.process()).willReturn("mocked");
    // Test code
  }
}

Common Patterns

Mocking Repository in Service Test

@SpringBootTest
class OrderServiceTest {
  @MockitoBean
  private OrderRepository orderRepository;
  
  @Autowired
  private OrderService orderService;
  
  @Test
  void shouldCreateOrder() {
    given(orderRepository.save(any())).willReturn(new Order(1L));
    
    Long id = orderService.createOrder(new OrderRequest());
    
    assertThat(id).isEqualTo(1L);
    verify(orderRepository).save(any(Order.class));
  }
}

Multiple Mocks of Same Type

Use bean names:

@MockitoBean(name = "primaryDataSource")
private DataSource primaryDataSource;

@MockitoBean(name = "secondaryDataSource")
private DataSource secondaryDataSource;

Migration from @MockBean

Before (Deprecated)

@MockBean
private OrderService orderService;

After (Spring Boot 4+)

@MockitoBean
private OrderService orderService;

Key Differences from Mockito @Mock

Feature @MockitoBean @Mock
Context integration Yes No
Spring lifecycle Participates None
Works with @Autowired Yes No
Test slice support Yes Limited

Best Practices

  1. Use @MockitoBean only when Spring context is involved
  2. For pure unit tests, use Mockito's @Mock or Mockito.mock()
  3. Always verify interactions that have side effects
  4. Don't verify simple queries (stubbing is enough)
  5. Reset mocks if test modifies shared mock state

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.