Catalog
affaan-m/springboot-tdd

affaan-m

springboot-tdd

Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

global
New~930
v1.1Saved May 11, 2026

Spring Boot TDD Workflow

TDD guidance for Spring Boot services with 80%+ coverage (unit + integration).

When to Use

  • New features or endpoints
  • Bug fixes or refactors
  • Adding data access logic or security rules

Workflow

  1. Write tests first (they should fail)
  2. Implement minimal code to pass
  3. Refactor with tests green
  4. Enforce coverage (JaCoCo)

Unit Tests (JUnit 5 + Mockito)

@ExtendWith(MockitoExtension.class)
class MarketServiceTest {
  @Mock MarketRepository repo;
  @InjectMocks MarketService service;

  @Test
  void createsMarket() {
    CreateMarketRequest req = new CreateMarketRequest("name", "desc", Instant.now(), List.of("cat"));
    when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0));

    Market result = service.create(req);

    assertThat(result.name()).isEqualTo("name");
    verify(repo).save(any());
  }
}

Patterns:

  • Arrange-Act-Assert
  • Avoid partial mocks; prefer explicit stubbing
  • Use @ParameterizedTest for variants

Web Layer Tests (MockMvc)

@WebMvcTest(MarketController.class)
class MarketControllerTest {
  @Autowired MockMvc mockMvc;
  @MockBean MarketService marketService;

  @Test
  void returnsMarkets() throws Exception {
    when(marketService.list(any())).thenReturn(Page.empty());

    mockMvc.perform(get("/api/markets"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.content").isArray());
  }
}

Integration Tests (SpringBootTest)

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class MarketIntegrationTest {
  @Autowired MockMvc mockMvc;

  @Test
  void createsMarket() throws Exception {
    mockMvc.perform(post("/api/markets")
        .contentType(MediaType.APPLICATION_JSON)
        .content("""
          {"name":"Test","description":"Desc","endDate":"2030-01-01T00:00:00Z","categories":["general"]}
        """))
      .andExpect(status().isCreated());
  }
}

Persistence Tests (DataJpaTest)

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(TestContainersConfig.class)
class MarketRepositoryTest {
  @Autowired MarketRepository repo;

  @Test
  void savesAndFinds() {
    MarketEntity entity = new MarketEntity();
    entity.setName("Test");
    repo.save(entity);

    Optional<MarketEntity> found = repo.findByName("Test");
    assertThat(found).isPresent();
  }
}

Testcontainers

  • Use reusable containers for Postgres/Redis to mirror production
  • Wire via @DynamicPropertySource to inject JDBC URLs into Spring context

Coverage (JaCoCo)

Maven snippet:

<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.14</version>
  <executions>
    <execution>
      <goals><goal>prepare-agent</goal></goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals><goal>report</goal></goals>
    </execution>
  </executions>
</plugin>

Assertions

  • Prefer AssertJ (assertThat) for readability
  • For JSON responses, use jsonPath
  • For exceptions: assertThatThrownBy(...)

Test Data Builders

class MarketBuilder {
  private String name = "Test";
  MarketBuilder withName(String name) { this.name = name; return this; }
  Market build() { return new Market(null, name, MarketStatus.ACTIVE); }
}

CI Commands

  • Maven: mvn -T 4 test or mvn verify
  • Gradle: ./gradlew test jacocoTestReport

Remember: Keep tests fast, isolated, and deterministic. Test behavior, not implementation details.

Files1
1 files · 1.0 KB

Select a file to preview

Overall Score

82/100

Grade

B

Good

Safety

88

Quality

84

Clarity

86

Completeness

72

Summary

A Spring Boot TDD workflow skill that guides developers through test-driven development using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. It provides structured patterns for unit tests, web layer tests, integration tests, and persistence tests with example code and configuration snippets.

Detected Capabilities

test executionjunit 5 test patternsmockito mockingspring boot test configurationsjacoco coverage reportingtestcontainers integration

Trigger Keywords

Phrases that MCP clients use to match this skill to user intent.

write junit testsspring boot testingtest-driven developmentmockito patternstest coverage goalsintegration test setup

Use Cases

  • Write unit tests for Spring Boot services before implementing features
  • Build web controller tests using MockMvc and Mockito
  • Implement integration tests with SpringBootTest and test profiles
  • Create persistence layer tests with DataJpaTest and Testcontainers
  • Achieve 80%+ code coverage with JaCoCo reporting
  • Test-drive bug fixes and refactors in Spring Boot applications

Quality Notes

  • Well-organized sections with clear hierarchy (Unit Tests, Web Layer, Integration, Persistence, Coverage)
  • Concrete, executable code examples for each testing pattern (AAA structure, MockMvc, DataJpaTest)
  • Covers testing layers comprehensively: unit, controller, integration, and data access
  • Includes both Maven and Gradle CI commands for different build systems
  • Emphasizes best practices: avoid partial mocks, prefer AssertJ for readability, use @ParameterizedTest for variants
  • Test data builder pattern included for maintainable test fixtures
  • Clear guidance on when to use this skill (new features, bugs, refactors)
  • Testcontainers approach documented with production-parity mirror guidance
  • Emphasis on speed, isolation, and determinism—foundational TDD principles
  • Brief but complete coverage section with JaCoCo Maven snippet
Model: claude-haiku-4-5-20251001Analyzed: May 11, 2026

Reviews

Add this skill to your library to leave a review.

No reviews yet

Be the first to share your experience.

Version History

v1.1

Content updated

2026-04-20

Latest
v1.0

Seeded from github.com/affaan-m/everything-claude-code

2026-03-16

Add affaan-m/springboot-tdd to your library

Command Palette

Search for a command to run...

affaan-m/springboot-tdd | SkillRepo