junit-testing
Skill4 starsChanged 9 months agoMITView on GitHub
JUnit 5 testing patterns including annotations, Mockito mocking, Spring Boot test slices, MockMvc, Testcontainers integration, and parameterized tests. Use when the user is writing Java tests, setting up test infrastructure, mocking dependencies, testing Spring controllers, or running integration tests with real databases. Trigger on any mention of JUnit, Mockito, @SpringBootTest, MockMvc, Testcontainers, or Java testing.
In this repository78 other files it gives its agents.
- AGENTS.mdAGENTS.md
- rules/agents.mdAGENTS.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/claude-initial-setup.mdcCursor rule
- parallel-task-executionSkill
- subagent-patternsSkill
- task-coordinationSkill
- agent-communicationSkill
- context-managementSkill
- multi-agent-orchestrationSkill
- deploy-strategiesSkill
- github-actions-guideSkill
- pipeline-patternsSkill
- anthropic-sdk-guideSkill
- prompt-engineeringSkill
- tool-use-patternsSkill
- automated-review-setupSkill
- pr-standardsSkill
- review-checklistSkill
- file-organizationSkill
- immutability-patternsSkill
- naming-conventionsSkill
- branching-strategySkill
- commit-conventionsSkill
- pr-workflowSkill
- migration-patternsSkill
- query-optimizationSkill
- schema-design-guideSkill
- error-tracingSkill
- log-analysisSkill
- systematic-debuggingSkill
- django-admin-customizationSkill
- django-orm-masterySkill
- drf-api-patternsSkill
- docker-compose-guideSkill
- dockerfile-best-practicesSkill
- multi-stage-buildsSkill
- express-error-handlingSkill
- middleware-patternsSkill
- rest-api-nodeSkill
- async-fastapiSkill
- dependency-injection-fastapiSkill
- pydantic-validationSkill
- concurrency-patterns-goSkill
- error-handling-goSkill
- idiomatic-goSkill
- automation-triggersSkill
- hook-recipesSkill
- pre-post-hooksSkill
- maven-gradle-guideSkill
- spring-boot-patternsSkill
- mcp-resource-patternsSkill
- mcp-server-creationSkill
- mcp-tool-designSkill
- context-optimizationSkill
- knowledge-persistenceSkill
- memory-patternsSkill
- caching-strategiesSkill
- lazy-loading-patternsSkill
- profiling-guideSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 2 are distinctive, and 0 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 122
Test controllers in isolation without starting the full application context.
- Distinctive: line 186
Run the same test logic with different inputs.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
JUnit 5 Testing Patterns
Patterns for writing effective unit, integration, and slice tests in Java.
When to Use
- User is writing JUnit 5 tests
- User needs to mock dependencies with Mockito
- User asks about Spring Boot test slices (@WebMvcTest, @DataJpaTest)
- User wants integration tests with real databases (Testcontainers)
- User needs parameterized tests for multiple inputs
Core Patterns
JUnit 5 Annotations and Lifecycle
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;
class UserServiceTest {
private UserService userService;
private UserRepository userRepository;
@BeforeEach
void setUp() {
userRepository = new InMemoryUserRepository();
userService = new UserService(userRepository);
}
@Test
@DisplayName("creates a user with valid input")
void createsUserWithValidInput() {
User result = userService.createUser(new CreateUserRequest("Alice", "alice@example.com"));
assertAll(
() -> assertNotNull(result.getId()),
() -> assertEquals("Alice", result.getName()),
() -> assertEquals("alice@example.com", result.getEmail())
);
}
@Test
@DisplayName("throws when email is already taken")
void throwsWhenEmailTaken() {
userRepository.save(new User("Bob", "bob@example.com"));
assertThrows(ConflictException.class,
() -> userService.createUser(new CreateUserRequest("Bob2", "bob@example.com")));
}
@Nested
@DisplayName("when user exists")
class WhenUserExists {
private User existingUser;
@BeforeEach
void setUp() {
existingUser = userRepository.save(new User("Alice", "alice@example.com"));
}
@Test
void findsById() {
Optional<User> found = userService.findById(existingUser.getId());
assertTrue(found.isPresent());
assertEquals("Alice", found.get().getName());
}
}
}Mockito -- Mocking Dependencies
Isolate the unit under test by mocking its collaborators.
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock private OrderRepository orderRepository;
@Mock private PaymentGateway paymentGateway;
@InjectMocks private OrderService orderService;
@Test
@DisplayName("places order and charges payment")
void placesOrderAndChargesPayment() {
var order = new Order("product-1", 2, 29_99L);
when(orderRepository.save(any(Order.class))).thenReturn(order);
when(paymentGateway.charge(anyLong())).thenReturn(new PaymentResult(true, "txn-123"));
assertNotNull(orderService.placeOrder(order));
verify(paymentGateway).charge(29_99L);
verify(orderRepository).save(order);
}
@Test
@DisplayName("rolls back order when payment fails")
void rollsBackWhenPaymentFails() {
when(paymentGateway.charge(anyLong())).thenReturn(new PaymentResult(false, null));
assertThrows(PaymentFailedException.class,
() -> orderService.placeOrder(new Order("product-1", 1, 50_00L)));
verify(orderRepository, never()).save(any());
}
}@WebMvcTest -- Controller Slice Tests
Test controllers in isolation without starting the full application context. Only the web layer is loaded.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired private MockMvc mockMvc;
@MockBean private UserService userService;
@Test
@DisplayName("GET /api/v1/users/{id} returns user")
void getUser() throws Exception {
when(userService.findById("1"))
.thenReturn(Optional.of(new UserResponse("1", "Alice", "alice@example.com")));
mockMvc.perform(get("/api/v1/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.name").value("Alice"));
}
@Test
@DisplayName("POST /api/v1/users validates request body")
void validateCreateUser() throws Exception {
mockMvc.perform(post("/api/v1/users")
.contentType("application/json")
.content("{\"name\":\"\",\"email\":\"not-an-email\"}"))
.andExpect(status().isBadRequest());
}
}Testcontainers -- Integration Tests with Real Databases
Spin up real database containers for integration tests. Tests are reliable and match production behavior.
@SpringBootTest
@Testcontainers
class UserRepositoryIntegrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("testdb").withUsername("test").withPassword("test");
@DynamicPropertySource
static void configureProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgres::getJdbcUrl);
registry.add("spring.datasource.username", postgres::getUsername);
registry.add("spring.datasource.password", postgres::getPassword);
}
@Autowired private UserRepository userRepository;
@Test
@DisplayName("persists and retrieves a user")
void persistsAndRetrieves() {
User saved = userRepository.save(new User("Alice", "alice@example.com"));
Optional<User> found = userRepository.findById(saved.getId());
assertTrue(found.isPresent());
assertEquals("Alice", found.get().getName());
}
}Parameterized Tests
Run the same test logic with different inputs. Reduces duplication.
class EmailValidatorTest {
private final EmailValidator validator = new EmailValidator();
@ParameterizedTest
@CsvSource({"alice@example.com, true", "bob@test.org, true", "invalid, false", "@no-local.com, false"})
void validatesEmail(String email, boolean expected) {
assertEquals(expected, validator.isValid(email));
}
@ParameterizedTest
@NullAndEmptySource
@ValueSource(strings = {" ", "\t"})
void rejectsBlankEmails(String email) {
assertFalse(validator.isValid(email));
}
@ParameterizedTest
@MethodSource("validEmailProvider")
void acceptsValidEmails(String email) { assertTrue(validator.isValid(email)); }
static Stream<String> validEmailProvider() {
return Stream.of("a@b.com", "user+tag@domain.co", "first.last@sub.domain.org");
}
}Anti-Patterns
- Testing implementation details -- Verifying private method calls or internal state. Test behavior (inputs and outputs), not how the code achieves the result.
- Overusing @SpringBootTest -- Loads the entire application context. Slow. Use slice annotations (@WebMvcTest, @DataJpaTest) to load only what you need.
- Not using @ExtendWith(MockitoExtension.class) -- Forgetting this means @Mock and @InjectMocks annotations are silently ignored, leading to NullPointerException.
- Sharing mutable state between tests -- Tests must be independent. Use @BeforeEach to reset state. Never rely on test execution order.
- Mocking everything including the class under test -- Only mock collaborators. The class under test should use its real implementation.
Quick Reference
| Category | Key APIs |
| Lifecycle | @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, @Nested |
| Assertions | assertEquals, assertTrue, assertThrows, assertAll, assertTimeout |
| Mockito | when().thenReturn(), verify(), any(), @Mock, @InjectMocks |
| Slices | @WebMvcTest (controllers), @DataJpaTest (JPA), @SpringBootTest (full) |
| Parameterized | @CsvSource, @ValueSource, @MethodSource, @NullAndEmptySource |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

