본문으로 건너뛰기
cccskills
무료GitHub에 공개

testing

Expert knowledge of testing patterns and strategies in melosys-api. Use when: (1) Writing unit tests with JUnit 5 or Kotest, (2) Setting up integration tests with Testcontainers, (3) Understanding the test base classes and hierarchy, (4) Using ArchUnit for architecture tests, (5) Configuring embedded Kafka for testing, (6) Understanding mock patterns and test utilities, (7) Creating test data with the forTest DSL.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(3)

  • SKILL.md13.0 KB
  • references/debugging.md6.9 KB
  • references/fortest-dsl.md13.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Testing Skill

Expert knowledge of testing patterns and strategies in melosys-api.

Quick Reference

Test Types

TypeFrameworkLocationSuffix
Unit testsJUnit 5, Kotest*/src/test/Test.kt
Integration testsSpring Boot Testintegrasjonstest/IT.kt
Architecture testsArchUnitarkitektur/IT.kt

*Test.kt classes can be plain Spring-free unit tests — they may still use the forTest DSL to build in-memory domain objects (no DB, no truncateAllTables). Only *IT.kt boot Spring and require the Testcontainers Oracle DB.

Test Commands

# Unit tests for a module
scripts/run-tests.sh -pl service -Dtest=MyServiceTest

# Integration tests without dependency rebuild
scripts/run-tests.sh -pl integrasjonstest --integration -Dtest=MyIT

# Integration tests with dependency rebuild
scripts/run-tests.sh -pl integrasjonstest -am --integration -Dtest=MyIT

Key Base Classes

ClassPurposeKey Features
OracleTestContainerBaseOracle DB containerTestcontainers, @BeforeEach truncateAllTables()
ComponentTestBaseFull component testsEmbeddedKafka, MockOAuth2
DataJpaTestBaseJPA-only testsLighter setup
MockServerTestBaseWithProsessManagerSaga testing + WireMockProsessManager (most ITs extend this)
JournalfoeringBaseJournalføring flowsJournalfoeringService, OppgaveService
AvgiftFaktureringTestBaseAvgift testsBilling setup

Test Base Class Hierarchy

The chain is linear — each class extends the one above it:

OracleTestContainerBase
    └── ComponentTestBase (@SpringBootTest)
            └── MockServerTestBaseWithProsessManager (+ WireMock, ProsessManager)
                    └── JournalfoeringBase
                            └── AvgiftFaktureringTestBase

Most integration tests extend MockServerTestBaseWithProsessManager, not ComponentTestBase directly. DataJpaTestBase is a separate, lighter JPA-only base for repository tests.

OracleTestContainerBase

Base class for tests needing Oracle database. Every integration test gets a clean database automatically: a @BeforeEach truncateAllTables() disables all foreign-key constraints, TRUNCATEs an explicit list of test-data tables (kodeverk/static tables are left alone), then re-enables the constraints. There is no per-test cleanup-registration API — tests do not need to register anything to clean up after themselves.

open class OracleTestContainerBase {

    @Autowired
    private lateinit var jdbcTemplate: JdbcTemplate

    /**
     * Tømmer alle tabeller før hver test for å sikre isolasjon.
     * BeforeEach (ikke AfterEach) gjør at man kan inspisere DB etter en test for feilsøking.
     */
    @BeforeEach
    fun truncateAllTables() {
        val tablesToTruncate = listOf(
            "PROSESSINSTANS_HENDELSER", "PROSESSINSTANS",  // Saksflyt først pga FK
            "AARSAVREGNING", "TRYGDEAVGIFTSPERIODE", "MEDLEMSKAPSPERIODE", "LOVVALG_PERIODE",
            // ... eksplisitt liste, child før parent ...
            "BEHANDLINGSRESULTAT", "BEHANDLING", "AKTOER", "FAGSAK"
        )
        // Deaktiver FK-constraints, TRUNCATE hver tabell, reaktiver constraints (via jdbcTemplate)
    }

    companion object {
        val oracleContainer = OracleContainer(
            DockerImageName.parse("ghcr.io/navikt/melosys-legacy-avhengigheter/oracle-xe:18.4.0-slim")
                .asCompatibleSubstituteFor("gvenzl/oracle-xe")
        )

        @DynamicPropertySource
        @JvmStatic
        fun oracleProperties(registry: DynamicPropertyRegistry) {
            if (useTestContainer()) {
                registry.add("spring.datasource.url") { oracleContainer.jdbcUrl }
                registry.add("spring.datasource.username") { oracleContainer.username }
                registry.add("spring.datasource.password") { oracleContainer.password }
                oracleContainer.start()
            }
        }
    }
}

Local DB Mode

For ARM Macs or faster tests:

export USE_LOCAL_DB=true

ComponentTestBase

Full component test with all dependencies mocked.

@ActiveProfiles("test")
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@SpringBootTest(
    classes = [Application::class],
    webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT
)
@EmbeddedKafka(
    topics = ["teammelosys.eessi.v1-local", "teammelosys.soknad-mottak.v1-local", ...]
)
@Import(KafkaTestConfig::class, KodeverkTestConfig::class)
@DirtiesContext
@EnableMockOAuth2Server
abstract class ComponentTestBase : OracleTestContainerBase()

Unleash (Feature Toggles)

val fakeUnleash: FakeUnleash by lazy {
    unleash.shouldBeInstanceOf<FakeUnleash>()
}

// Enable/disable features
fakeUnleash.enable("MY_FEATURE")
fakeUnleash.disable("MY_FEATURE")

Mock Verification

ComponentTestBase exposes a mockVerificationClient and calls clear() in @BeforeEach, so each test starts with empty mock state. The client exposes domain queries — there is no generic verify(path, count) method.

protected val mockVerificationClient: MockVerificationClient by lazy {
    MockVerificationClient(MelosysMockContainerConfig.getBaseUrl())
}

// Verify what was sent to the mock via domain queries:
mockVerificationClient.sakCount() shouldBe 1
mockVerificationClient.sedForRinaSak(rinaSaksnummer)
    .shouldContainInOrder("A012", "X008", "A004")
mockVerificationClient.medl().shouldHaveSize(1)
// Other queries: saker(), sakByFagsakNr(), oppgaver(), oppgaverByType(),
// journalposter(), bucInfo(), saksrelasjoner(), summary()

ArchUnit Tests

Architecture tests enforcing layered architecture.

@AnalyzeClasses(packages = ["no.nav.melosys"])
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ArkitekturTestIT {

    @ArchTest
    val `Melosys has layered architecture`: ArchRule = layeredArchitecture()
        .consideringOnlyDependenciesInAnyPackage("no.nav.melosys")
        .layer("Controller").definedBy("..tjenester.gui..")
        .layer("Service").definedBy("..service..")
        .layer("Integrations").definedBy("..integrasjon..")
        .layer("Persistence").definedBy("..repository..")
        .whereLayer("Controller").mayNotBeAccessedByAnyLayer()
        .whereLayer("Service").mayOnlyBeAccessedByLayers("Controller")
}

Embedded Kafka Testing

Test Configuration

@TestConfiguration
class KafkaTestConfig {
    @Bean
    @Qualifier("melosysEessiMelding")
    fun melosysEessiMeldingKafkaTemplate(
        kafkaProperties: KafkaProperties,
        objectMapper: ObjectMapper?
    ): KafkaTemplate<String, MelosysEessiMelding> {
        val props = kafkaProperties.buildConsumerProperties(null)
        val producerFactory = DefaultKafkaProducerFactory(
            props, StringSerializer(), JsonSerializer(objectMapper)
        )
        return KafkaTemplate(producerFactory)
    }
}

Sending Test Messages

@Autowired
@Qualifier("melosysEessiMelding")
private lateinit var kafkaTemplate: KafkaTemplate<String, MelosysEessiMelding>

fun sendTestMessage() {
    kafkaTemplate.send("teammelosys.eessi.v1-local", message)
}

Consuming Test Messages

@Component
class MelosysHendelseKafkaConsumer {
    private val records: BlockingQueue<ConsumerRecord<String, MelosysHendelse>> = LinkedBlockingQueue()

    @KafkaListener(topics = ["\${kafka.aiven.melosys-hendelser.topic}"])
    private fun melosysHendelseListener(record: ConsumerRecord<String, MelosysHendelse>) {
        records.add(record)
    }

    fun waitForMessage(timeout: Duration): MelosysHendelse? =
        records.poll(timeout.toMillis(), TimeUnit.MILLISECONDS)?.value()
}

Unit Test Patterns

Tests follow given/when/then: setup, the call under test, then assertions. Separate the three phases with a blank line, not with // Given / // When / // Then or // Arrange / // Act / // Assert comments.

JUnit 5 Pattern

@ExtendWith(MockitoExtension::class)
class MyServiceTest {

    @Mock
    private lateinit var repository: MyRepository

    @InjectMocks
    private lateinit var service: MyService

    @Test
    fun `should do something`() {
        whenever(repository.findById(any())).thenReturn(Optional.of(entity))

        val result = service.doSomething(id)

        assertThat(result).isNotNull()
        verify(repository).findById(id)
    }
}

Kotest Pattern

class MyServiceTest : FunSpec({

    val repository = mockk<MyRepository>()
    val service = MyService(repository)

    test("should do something") {
        every { repository.findById(any()) } returns Optional.of(entity)

        val result = service.doSomething(id)

        result shouldNotBe null
        verify { repository.findById(id) }
    }
})

Integration Test Pattern

Most integration tests extend MockServerTestBaseWithProsessManager. The DB is truncated in @BeforeEach (via OracleTestContainerBase.truncateAllTables()), so each test starts from an empty database — there is no per-test cleanup to register.

class MyServiceIT : MockServerTestBaseWithProsessManager() {

    @Autowired
    private lateinit var service: MyService

    @Test
    fun `should integrate with database`() {
        val fagsak = createTestFagsak()

        val result = service.process(fagsak.id)

        assertThat(result).isNotNull()
    }
}

Test Utilities

Database isolation

Integration tests do not register cleanup. OracleTestContainerBase.truncateAllTables() runs in @BeforeEach: it reads all enabled foreign-key constraints from user_constraints, disables them, TRUNCATEs an explicit list of test-data tables (child tables before parents), then re-enables the constraints. Kodeverk and other static-data tables are deliberately excluded from the truncate list. The net effect: every test starts with a clean, empty set of business tables and can inspect leftover data afterwards for debugging.

Test Data Builders

// E2ETestDataService in saksflyt module
val fagsak = e2eTestDataService.opprettFagsak(
    sakstema = Sakstemaer.MEDLEMSKAP_LOVVALG,
    sakstype = Sakstyper.EU_EOS
)

forTest DSL

Type-safe Kotlin DSL for creating test data with sensible defaults and nested entity support.

Full reference: See references/fortest-dsl.md

Quick Examples

// Simple entity
val fagsak = Fagsak.forTest {
    tema = Sakstemaer.TRYGDEAVGIFT
    type = Sakstyper.FTRL
}

// Nested entities
val behandling = Behandling.forTest {
    fagsak {
        medBruker()
        medVirksomhet()
    }
    mottatteOpplysninger {
        type = Mottatteopplysningertyper.SØKNAD_A1_YRKESAKTIVE_EØS
        soeknad { landkoder("BE", "NL") }
    }
}

// Complex hierarchy
val behandlingsresultat = Behandlingsresultat.forTest {
    behandling { fagsak { type = Sakstyper.FTRL } }
    medlemskapsperiode {
        fom = LocalDate.of(2023, 1, 1)
        tom = LocalDate.of(2023, 12, 31)
        trygdeavgiftsperiode { trygdesats = 6.8.toBigDecimal() }
    }
}

Available Factories

EntityFactory
FagsakFagsakTestFactory
BehandlingBehandlingTestFactory
BehandlingsresultatBehandlingsresultatTestFactory
MedlemskapsperiodeMedlemskapsperiodeTestFactory
TrygdeavgiftsperiodeTrygdeavgiftsperiodeTestFactory
ProsessinstansProsessinstansTestFactory

KafkaOffsetChecker

offsetIncreased(topic, groupId) { ... } runs the block, then returns how much the consumer group's committed offset grew — useful to assert that a message was (or was NOT) consumed.

val delta = kafkaOffsetChecker.offsetIncreased(topic, groupId) {
    kafkaTemplate.send("teammelosys.eessi.v1-local", message)
    // wait for processing to complete...
}
delta shouldBe 0  // e.g. assert the message was NOT committed because it failed

Test Profiles

application-test.yml

spring:
  datasource:
    url: jdbc:oracle:thin:@//localhost:1521/XEPDB1
  kafka:
    bootstrap-servers: ${spring.embedded.kafka.brokers}

melosys:
  mock-enabled: true

Debugging Tests

Full reference: See references/debugging.md

Quick commands:

# Single test
scripts/run-tests.sh -pl service -Dtest=MyServiceTest#testMethodName

# Debug mode (attach debugger to port 5005)
mvn -pl service test -Dtest=MyTest -Dmaven.surefire.debug

# View full logs
cat /tmp/mvn.log

Related Skills

  • kafka: Kafka testing patterns
  • database: Database schema for test data
  • saksflyt: Saga testing patterns

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Expert knowledge of Altinn A1 application processing for posted workers in melosys-api. Use when: (1) Understanding Altinn søknad/skjema processing, (2) Debugging MedlemskapArbeidEOS form mapping, (3) Understanding SoeknadMapper transformations, (4) Investigating posted worker application issues, (5) Understanding the MOTTAK_SOKNAD_ALTINN saga flow.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Employer/Employment integration (EREG/AAREG) in melosys-api. Use when: (1) Working with organization data from EREG (Enhetsregisteret), (2) Working with employment data from AAREG (Arbeidsforhold), (3) Understanding employer/organization lookup, (4) Debugging employer or employment issues, (5) Understanding the mapping between register data and domain models. Triggers: orgnummer, arbeidsforhold, EREG, AAREG, Enhetsregisteret, registeropplysninger, ansettelsesperiode, saksopplysning.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Modular monolith architecture overview for melosys-api. Use when needing to understand module structure, dependencies between modules, where to place new code, or when changes in one module might affect others. Triggers: "architecture", "module dependencies", "where should I put", "which modules", "dependency graph".

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Behandling (case treatment) domain in melosys-api. Use when: (1) Understanding the behandling lifecycle and status transitions, (2) Debugging issues with behandling creation, status changes, or closure, (3) Understanding relationships between Fagsak, Behandling, and Behandlingsresultat, (4) Investigating why a behandling is stuck or has wrong status, (5) Understanding Behandlingstyper, Behandlingstema, Behandlingsstatus enums, (6) Debugging journalføring or SED-triggered behandling creation, (7) Understanding behandling creation via saksflyt sagas.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

Expert knowledge of Behandlingsresultat (treatment result) domain in melosys-api. Use when: (1) Understanding result types and their meaning (FASTSATT_LOVVALGSLAND, MEDLEM_I_FOLKETRYGDEN, etc.), (2) Working with periods - Lovvalgsperiode, Medlemskapsperiode, Anmodningsperiode, Utpekingsperiode, (3) Debugging vedtak/decision metadata, criteria evaluation, or social insurance charges, (4) Understanding EU/EEA coordination logic and Article 16 exception handling, (5) Working with trygdeavgift (social insurance charge) calculations.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

brev

무료

Expert knowledge of Brev (letter generation) in melosys-api. Use when: (1) Producing letters and decision documents (vedtaksbrev), (2) Understanding Dokgen templates and mapping, (3) Configuring letter recipients and distribution, (4) Debugging letter generation issues, (5) Adding new letter types or templates.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

navikt/melosys-api22026년 10월 21일 업데이트

navikt의 스킬 모두 보기

이 스킬의 문제 신고