跳到正文
cccskills
免费在 GitHub 公开

jvm-testing

JUnit 5, Mockito, AssertJ, and Testcontainers patterns for any JVM project. Covers test structure, parameterised tests, mocking discipline, fluent assertions, and integration testing with real containers. Stack-agnostic — referenced by every Java plugin in the marketplace. Use this skill to: - Write clear, maintainable unit tests with JUnit 5. - Mock dependencies with Mockito without overusing mocks. - Write expressive assertions with AssertJ. - Spin up real infrastructure (DBs, message brokers) with Testcontainers for integration tests. Do NOT use this skill for: - Spring-specific test slices (@SpringBootTest, @WebMvcTest, @DataJpaTest — those are in spring-boot-plugin skills). - Framework-specific mocking utilities (MockMvc, WebTestClient).

中文简介正在准备中。当前显示原文说明。

集成工具PostgreSQL

实测评分 未实测

查看安装方法

包含的文件(1)

  • SKILL.md8.3 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

JVM Testing Patterns (stack-agnostic)

JUnit 5 fundamentals

import org.junit.jupiter.api.*;
import static org.assertj.core.api.Assertions.*;

class UserServiceTest {

    private UserRepository repository;
    private UserService service;

    @BeforeEach
    void setUp() {
        repository = mock(UserRepository.class);
        service = new UserService(repository);
    }

    @Test
    void registerUser_withValidData_returnsActiveUser() {
        // Arrange
        var command = new RegisterUserCommand("alice@example.com", "Secret1!");
        when(repository.existsByEmail("alice@example.com")).thenReturn(false);
        when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));

        // Act
        var user = service.register(command);

        // Assert
        assertThat(user.email()).isEqualTo("alice@example.com");
        assertThat(user.isActive()).isTrue();
    }

    @Test
    void registerUser_withDuplicateEmail_throwsException() {
        when(repository.existsByEmail(any())).thenReturn(true);

        assertThatThrownBy(() -> service.register(new RegisterUserCommand("dup@example.com", "pass")))
            .isInstanceOf(DuplicateEmailException.class)
            .hasMessageContaining("dup@example.com");
    }
}

Test method naming: methodName_condition_expectedOutcome (readable without comments). @DisplayName for BDD-style prose when the method name would be unwieldy.

AAA structure: Arrange → Act → Assert. Separate with blank lines (no comments needed when the structure is clear).

One assertion concept per test. Multiple assertThat calls are fine when they all verify the same behaviour.

Parameterised tests

@ParameterizedTest
@ValueSource(strings = { "", " ", "\t", "\n" })
void isBlank_variousBlankStrings_returnsTrue(String input) {
    assertThat(StringUtils.isBlank(input)).isTrue();
}

@ParameterizedTest
@CsvSource({
    "alice@example.com, true",
    "not-an-email,      false",
    "@nodomain.com,     false",
})
void isValidEmail(String email, boolean expected) {
    assertThat(validator.isValid(email)).isEqualTo(expected);
}

@ParameterizedTest
@MethodSource("invalidCommands")
void register_withInvalidCommand_throws(RegisterUserCommand command) {
    assertThatThrownBy(() -> service.register(command))
        .isInstanceOf(ValidationException.class);
}

static Stream<RegisterUserCommand> invalidCommands() {
    return Stream.of(
        new RegisterUserCommand(null, "pass"),
        new RegisterUserCommand("", "pass"),
        new RegisterUserCommand("user@example.com", "")
    );
}

AssertJ — fluent assertions

Prefer AssertJ over JUnit's assertEquals — it gives better failure messages and supports fluent chaining.

// Collections
assertThat(users)
    .hasSize(3)
    .extracting(User::email)
    .containsExactlyInAnyOrder("a@x.com", "b@x.com", "c@x.com");

// Exceptions
assertThatThrownBy(() -> service.delete(unknownId))
    .isInstanceOf(EntityNotFoundException.class)
    .hasMessageContaining(unknownId.toString());

// Optional
assertThat(service.findById(42L))
    .isPresent()
    .hasValueSatisfying(u -> assertThat(u.name()).isEqualTo("Alice"));

// Soft assertions — collect all failures
assertSoftly(softly -> {
    softly.assertThat(order.status()).isEqualTo(OrderStatus.CONFIRMED);
    softly.assertThat(order.total()).isEqualByComparingTo("99.99");
    softly.assertThat(order.items()).hasSize(2);
});

Never use Assertions.assertTrue(a.equals(b)) — the failure message shows only "expected true" with no values. Use assertThat(a).isEqualTo(b).

Mockito discipline

// Constructor injection — preferred (no reflection magic, works without Spring)
var repo = mock(UserRepository.class);
var service = new UserService(repo);

// Stubbing — be specific
when(repo.findById(42L)).thenReturn(Optional.of(testUser));

// Argument matchers — use when value doesn't matter; mix carefully
when(repo.existsByEmail(anyString())).thenReturn(false);

// Capture for verification
var captor = ArgumentCaptor.forClass(User.class);
verify(repo).save(captor.capture());
assertThat(captor.getValue().email()).isEqualTo("alice@example.com");

// Verify interaction count
verify(repo, times(1)).save(any());
verify(repo, never()).delete(any());

Avoid @InjectMocks when possible — prefer explicit constructor injection in tests; it makes dependencies visible and avoids field-injection surprises.

Do not mock value objects or simple data classes. Only mock boundaries (repositories, HTTP clients, external services).

Testcontainers — integration tests with real infrastructure

@Testcontainers
class UserRepositoryIT {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test");

    @BeforeAll
    static void configure() {
        // Wire datasource — exact mechanism depends on framework
        System.setProperty("spring.datasource.url", postgres.getJdbcUrl());
        System.setProperty("spring.datasource.username", postgres.getUsername());
        System.setProperty("spring.datasource.password", postgres.getPassword());
    }

    @Test
    void saveAndFindById_roundtrip() {
        var repo = buildRepository();
        var user = new User(null, "alice@example.com");

        var saved = repo.save(user);
        var found = repo.findById(saved.id());

        assertThat(found).isPresent()
            .hasValueSatisfying(u -> assertThat(u.email()).isEqualTo("alice@example.com"));
    }
}

Static containers (static field + @Container) are reused across all tests in the class — faster than per-test containers. Reuse across test classes via a shared base class or singleton pattern.

Separate integration tests from unit tests. Maven Failsafe plugin runs *IT.java in verify; Gradle can use source sets or a custom test task.

<!-- Maven: integration tests run in verify phase -->
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Test organisation conventions

src/
├── main/java/com/example/...
└── test/java/com/example/
    ├── unit/                   # optional subpackage grouping
    │   └── UserServiceTest.java
    └── integration/
        └── UserRepositoryIT.java

Mirror the main package structure — each class under test has a corresponding test class in the same package hierarchy.

Test class naming:

  • Unit tests: {Subject}Test
  • Integration tests: {Subject}IT
  • Slice tests (Spring): {Subject}Tests (Spring convention)

Coverage target

Aim for ≥ 80 % line coverage on business logic (services, domain objects). Framework glue code (configuration, main class) is excluded. Use JaCoCo to measure:

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

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Angular 18-21 project structure, standalone components vs NgModule, control flow (@if/@for/@switch + *ngIf/*ngFor legacy), decorators, dependency injection (inject() function), lifecycle hooks, pipes, Angular Universal SSR pointer. Use this skill to: - Detect project style (standalone vs NgModule) and apply matching patterns. - Pick correct decorators and DI approach. - Use modern control flow (@if/@for/@switch) in Angular 17+ projects. - Apply `inject()` function over constructor injection where appropriate. - Wire bootstrap correctly (bootstrapApplication for standalone, AppModule for legacy). Do NOT use this skill for: - State management (see angular-state-and-rx). - Routing (see angular-routing). - Forms (see angular-forms). - Testing (see angular-testing).

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

Angular forms: Reactive Forms (preferred — typed FormGroup/FormControl since Angular 14, FormBuilder, custom + async validators, FormArray, multi-step) and Template-driven (`[(ngModel)]` + FormsModule). Validation strategies, server error mapping, accessibility. Use this skill to: - Build Reactive Forms with typed FormGroup/FormControl. - Use FormBuilder для concise syntax. - Implement custom synchronous and async validators. - Wire FormArray for dynamic field lists. - Map server errors back to form fields. - Pick Reactive vs Template-driven (prefer Reactive). Do NOT use this skill for: - General conventions (see angular-conventions). - State management beyond forms (see angular-state-and-rx). - Routing (see angular-routing). - Testing forms (see angular-testing).

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

Angular Router (built-in `@angular/router`) — route configuration for standalone and NgModule projects, functional guards (Angular 14.1+), lazy loading, route resolvers, typed params via signals/observables, programmatic navigation, route data and meta. Use this skill to: - Configure routes (standalone-style or NgModule-style). - Use functional guards (canActivate as function, preferred over class-based in 17+). - Lazy-load components or feature modules. - Implement auth guards via route meta + functional guards. - Read params/queries via `inject(ActivatedRoute)` + signals or RxJS. Do NOT use this skill for: - General conventions (see angular-conventions). - State management (see angular-state-and-rx). - Forms (see angular-forms). - Testing routes (see angular-testing).

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

State management for Angular 18-21: signals (signal/computed/effect), services-as-state, NgRx Store + Effects + Selectors, NgRx Component Store, NgRx Signals (newer signal-based store). RxJS essentials — operators, async pipe, takeUntilDestroyed, signal/observable interop. Use this skill to: - Pick the right state tool (signals / services / NgRx variant / vue-query equivalent). - Use signals correctly (signal/computed/effect — when each). - Build a Pinia-style service-as-state singleton. - Set up NgRx Store + Effects + Selectors. - Use RxJS without leaking subscriptions (async pipe, takeUntilDestroyed, Subject patterns). - Bridge signals ↔ observables via toSignal / toObservable. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing state (see angular-routing). - Form state (see angular-forms). - Testing state (see angular-testing).

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

Testing Angular 18-21: TestBed, component harnesses (@angular/cdk/testing), Karma+Jasmine (default historical) vs Jest (jest-preset-angular, modern), Angular Testing Library (RTL-style). HttpClient mocking via HttpTestingController. NgRx Effects testing. Cypress / Playwright e2e. Use this skill to: - Detect runner (Karma+Jasmine vs Jest) and configure correctly. - Write component tests with TestBed. - Use component harnesses for Material / custom UI components. - Mock HttpClient via provideHttpClientTesting + HttpTestingController. - Test signal-based inputs with componentRef.setInput(). - Test NgRx Effects with provideMockActions. Do NOT use this skill for: - General Angular conventions (see angular-conventions). - Routing patterns broadly (see angular-routing — covers testing routes briefly). - Form patterns broadly (see angular-forms).

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

Shared conventions for every SDLC development-phase architect agent: hard rules, code quality bar, workflow steps (superpowers invocation, spec reading, codebase exploration, verification), and the report/compact-summary contract. Architects load this skill first, then apply their stack-specific instructions on top.

中文简介正在准备中。当前显示原文说明。

AratKruglik/claude-sdlc472026年10月17日 更新

查看 AratKruglik 的全部技能

报告此技能的问题