一键导入
java-junit
Best practices for JUnit 5 unit testing, including data-driven tests and modern patterns. Trigger: When writing JUnit tests, creating unit tests, or need testing best practices.
菜单
Best practices for JUnit 5 unit testing, including data-driven tests and modern patterns. Trigger: When writing JUnit tests, creating unit tests, or need testing best practices.
Pre-built UI component libraries for server-rendered HTML: Preline UI, HyperUI, Flowbite. Modals, tables, forms, navbars, dropdowns — no React, no build step. Trigger: UI components, component library, Preline, HyperUI, Flowbite, Tailwind CSS components, pre-built UI.
Server-side web UI with Spring Boot: Thymeleaf templates, HTMX for dynamic interactions, Alpine.js for client-side behavior. No React, no webpack. Trigger: Thymeleaf, HTMX, Alpine.js, Spring MVC template, server-side rendering, web UI.
REST API design best practices: resource naming, versioning, error handling, pagination, HATEOAS, rate limiting, OpenAPI documentation. Trigger: API design, REST API, endpoint, OpenAPI, RESTful, API versioning, or API documentation.
Docker and containerization best practices: multi-stage builds, docker-compose, networking, volumes, security, and image optimization. Trigger: Docker, Dockerfile, docker-compose, container, image build, or containerization.
General database design principles: modeling, normalization, indexing, naming conventions, migrations, and query optimization. Trigger: Database design, data modeling, schema design, table design, or migration planning.
Comprehensive best practices for developing high-quality Spring Boot applications with production-ready patterns. Trigger: When developing Spring Boot applications, need best practices, or working with Spring framework.
| name | java-junit |
| description | Best practices for JUnit 5 unit testing, including data-driven tests and modern patterns. Trigger: When writing JUnit tests, creating unit tests, or need testing best practices. |
| license | Apache-2.0 |
| metadata | {"author":"vekzz-dev","version":"1.1"} |
src/test/javajunit-jupiter-api, junit-jupiter-engine, and junit-jupiter-params for parameterized testsmvn test or gradle testTest suffix, e.g., CalculatorTest for a Calculator class@Test for test methodsmethodName_should_expectedBehavior_when_scenario@BeforeEach and @AfterEach for per-test setup and teardown@BeforeAll and @AfterAll for per-class setup and teardown (must be static methods)@DisplayName to provide a human-readable name for test classes and methodsclass CalculatorTest {
private Calculator calculator;
@BeforeEach
void setUp() {
calculator = new Calculator();
}
@Test
@DisplayName("Should add two positive numbers")
void add_shouldReturnSum_whenBothPositive() {
// Arrange
int a = 3, b = 5;
// Act
int result = calculator.add(a, b);
// Assert
assertEquals(8, result);
}
@Test
@DisplayName("Should throw exception when dividing by zero")
void divide_shouldThrowException_whenDenominatorIsZero() {
assertThrows(ArithmeticException.class,
() -> calculator.divide(10, 0),
"Division by zero should throw");
}
}
@ParameterizedTest to mark a method as a parameterized test@ValueSource for simple literal values (strings, ints, etc.)@MethodSource to refer to a factory method that provides test arguments as a Stream, Collection, etc.@CsvSource for inline comma-separated values@CsvFileSource to use a CSV file from the classpath@EnumSource to use enum constants@ParameterizedTest
@ValueSource(ints = {1, 2, 3, 5, 8, 13})
@DisplayName("Should identify Fibonacci numbers")
void isFibonacci_shouldReturnTrue_forFibonacciNumbers(int number) {
assertTrue(calculator.isFibonacci(number));
}
@ParameterizedTest
@CsvSource({
"4, 2, 2",
"10, 3, 1",
"7, 5, 2"
})
@DisplayName("Should compute modulo for various inputs")
void modulo_shouldReturnRemainder(int dividend, int divisor, int expected) {
assertEquals(expected, calculator.modulo(dividend, divisor));
}
@ParameterizedTest
@MethodSource("provideOrderStatuses")
@DisplayName("Should return correct display name for each status")
void getDisplayName_shouldReturnCorrectLabel(OrderStatus status, String expected) {
assertEquals(expected, status.getDisplayName());
}
static Stream<Arguments> provideOrderStatuses() {
return Stream.of(
Arguments.of(OrderStatus.PENDING, "Pending"),
Arguments.of(OrderStatus.SHIPPED, "Shipped"),
Arguments.of(OrderStatus.DELIVERED, "Delivered")
);
}
org.junit.jupiter.api.Assertions (e.g., assertEquals, assertTrue, assertNotNull)assertThat(...).is...)assertThrows or assertDoesNotThrow to test for exceptionsassertAll to ensure all assertions are checked before the test fails@Test
@DisplayName("Should create order with all required fields")
void createOrder_shouldSetAllFields() {
Order order = orderService.create("customer-1", List.of("item-a"), 2990);
assertAll("order fields",
() -> assertEquals("customer-1", order.getCustomerId(), "customer id"),
() -> assertEquals(2, order.getItemCount(), "item count"),
() -> assertNotNull(order.getCreatedAt(), "creation timestamp"),
() -> assertEquals(OrderStatus.PENDING, order.getStatus(), "initial status")
);
}
// AssertJ example
@Test
@DisplayName("Should return orders sorted by date")
void findRecentOrders_shouldReturnSortedResults() {
List<Order> orders = orderService.findRecent(7);
assertThat(orders)
.isNotEmpty()
.hasSizeLessThanOrEqualTo(50)
.extracting(Order::getStatus)
.contains(OrderStatus.SHIPPED);
}
@Mock and @InjectMocks annotations from Mockito to simplify mock creation and injection@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private PaymentGateway paymentGateway;
@Mock
private InventoryClient inventoryClient;
@InjectMocks
private OrderService orderService;
@Test
@DisplayName("Should process payment when placing order")
void placeOrder_shouldProcessPayment() {
// Arrange
when(inventoryClient.isAvailable("item-1")).thenReturn(true);
when(paymentGateway.charge(any(Payment.class)))
.thenReturn(new PaymentResult("tx-123", PaymentStatus.SUCCESS));
// Act
Order order = orderService.placeOrder("customer-1", "item-1");
// Assert
assertThat(order.getTransactionId()).isEqualTo("tx-123");
verify(paymentGateway).charge(any(Payment.class));
}
@Test
@DisplayName("Should throw when inventory is insufficient")
void placeOrder_shouldThrow_whenItemUnavailable() {
when(inventoryClient.isAvailable("item-1")).thenReturn(false);
assertThrows(InsufficientInventoryException.class,
() -> orderService.placeOrder("customer-1", "item-1"));
verify(paymentGateway, never()).charge(any());
}
}
@Tag to categorize tests (e.g., @Tag("fast"), @Tag("integration"))@TestMethodOrder(MethodOrderer.OrderAnnotation.class) and @Order to control test execution order when strictly necessary@Disabled to temporarily skip a test method or class, providing a reason@Nested to group tests in a nested inner class for better organization and structure@DisplayName("OrderService")
class OrderServiceTest {
@Nested
@DisplayName("placeOrder")
class PlaceOrder {
@Test
@DisplayName("Should create order successfully")
void shouldCreateOrder() { }
@Test
@DisplayName("Should reject duplicate orders")
void shouldRejectDuplicate() { }
}
@Nested
@DisplayName("cancelOrder")
class CancelOrder {
@Test
@DisplayName("Should cancel pending order")
void shouldCancelPending() { }
@Test
@DisplayName("Should throw when order is already shipped")
void shouldThrowWhenShipped() { }
}
}
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=CalculatorTest
# Run tests with specific tag
mvn test -Dgroups=fast
# Run tests with Gradle
gradle test
# Run specific test with Gradle
gradle test --tests CalculatorTest
For up-to-date information on JUnit 5 and AssertJ:
Resolve the libraryId - Use context7_resolve-library-id:
libraryName: "junit 5", "assertj", or "mockito"query: what you need (e.g., "parameterized tests", "assertions")Query the docs - Use context7_query-docs:
libraryId: "/junit/junit5" or "/assertj/assertj"query: your specific questionBefore writing tests, consult Context7 to get updated examples.