Spring › Wanted-Challenge

Testing Spring Boot APIs with Kotest and ArchUnit

Organize Spring Boot integration tests with Kotest and fixtures, catch false-positive MockMvc assertions, and enforce package boundaries with ArchUnit.

Testing Spring Boot APIs with Kotest and ArchUnit

Some of my Kotlin MockMvc tests passed even when the endpoint returned an error. I fixed the missing matcher registration, then separated HTTP integration tests, token unit tests, and architecture tests so each checked a different boundary.

The examples use Java 21, Kotlin 1.9.25, Spring Boot 3.5.16, Kotest 5.9.1, Fixture Monkey 1.2.4, and ArchUnit 1.4.1.

Reusing the Spring test context

An endpoint can have several success and failure cases, such as 201 for creation or 401 and 403 for two different security outcomes. Kotest DescribeSpec gives each endpoint a describe block with individual it cases. I registered SpringExtension once through AbstractProjectConfig to keep the test classes focused on behavior.

1
2
3
4
5
6
7
8
9
// src/test/kotlin/org/project/portfolio/config/KotestProjectConfig.kt
package org.project.portfolio.config

import io.kotest.core.config.AbstractProjectConfig
import io.kotest.extensions.spring.SpringExtension

class KotestProjectConfig : AbstractProjectConfig() {
    override fun extensions() = listOf(SpringExtension)
}

I removed broad @DirtiesContext use from the integration tests. Discarding the context can cause Hibernate and the rest of the application to restart, reducing the benefit of Spring’s test-context cache. It can also disturb a shared H2 database when jdbc:h2:mem:testdb;MODE=PostgreSQL;DB_CLOSE_DELAY=-1 is paired with ddl-auto: create-drop.

Tests that run synchronously in the test-managed transaction use @Transactional rollback for isolation. Data committed from REQUIRES_NEW or a background listener can outlive that rollback. Use explicit cleanup for such tests, and watch for requests that execute on another thread or another process.

Combining fixtures with explicit test inputs

Gradle’s java-test-fixtures plugin puts reusable data factories in src/testFixtures/kotlin. I use Fixture Monkey with KotlinPlugin and JakartaValidationPlugin for DTO properties that only need valid sample values.

Testing on the JVM is a rich subject matter. There are many different testing libraries and frameworks, as well as many different types of test. All need to be part of the build, whether they are executed frequently or infrequently. This chapter is dedicated to explaining how Gradle handles differing requirements between and within builds, with significant coverage of how it integrates with the two most common testing frameworks: JUnit and TestNG.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/testFixtures/kotlin/ArticleFixture.kt
import com.navercorp.fixturemonkey.FixtureMonkey
import com.navercorp.fixturemonkey.api.plugin.SimpleValueJqwikPlugin
import com.navercorp.fixturemonkey.jakarta.validation.plugin.JakartaValidationPlugin
import com.navercorp.fixturemonkey.kotlin.KotlinPlugin
import com.navercorp.fixturemonkey.kotlin.giveMeBuilder
import org.project.portfolio.article.domain.Article
import org.project.portfolio.article.presentation.request.ArticleForm
import java.time.Instant

object ArticleFixture {
    private val fixtureMonkey: FixtureMonkey = FixtureMonkey.builder()
        .plugin(KotlinPlugin())
        .plugin(SimpleValueJqwikPlugin())
        .plugin(JakartaValidationPlugin())
        .build()

    fun getRandomArticle(authorId: Long): ArticleForm {
        return fixtureMonkey.giveMeBuilder<ArticleForm>()
            .set("images", null)
            .set("authorId", authorId)
            .sample()
    }

    fun createArticle(
        articleForm: ArticleForm? = getRandomArticle(1)[0],
        authorId: Long = 1L,
        articleId: Long = 1L,
        createdAt: Instant = Instant.now(),
    ): Article {
        return Article(
            id = articleId,
            title = articleForm?.title ?: "An article title",
            content = articleForm?.content ?: "The article body",
            images = listOf(),
            authorId = authorId,
        ).apply {
            this.createdAt = createdAt
        }
    }
}

A search test must control the keyword and the fields it can match. A sorting test needs known values and order. I set those properties explicitly and generate only the surrounding valid data. That keeps random generation from deciding whether the assertion is satisfied.

Registering the MockMvc assertions

The broken test used a Java result matcher inside the Kotlin DSL. It looked like a status assertion and appeared to pass even when the endpoint returned 404 or 500.

1
2
3
4
5
6
// Incorrect: this does not register an assertion
mockMvc.get("/api/v1/articles") {
    contentType = MediaType.APPLICATION_JSON
}.andExpect {
    status().isOk // The Java method creates a ResultMatcher that is discarded
}

ResultActionsDsl.andExpect runs a MockMvcResultMatchersDsl lambda. Calling the Kotlin status { isOk() } block registers a matcher in that DSL. Calling Java’s MockMvcResultMatchers.status().isOk returns a matcher. If the code discards that return value, the DSL has nothing to execute.

FormWhat happens
mockMvc.get { }.andExpect { status().isOk }A returned matcher is discarded
mockMvc.get { }.andExpectAll { status { isOk() } }The Kotlin DSL registers and executes the assertion
mockMvc.perform(...).andExpectAll(status().isCreated)The Java API receives a matcher argument and executes it

I use andExpectAll when one HTTP scenario needs several independent assertions. For multipart requests made through mockMvc.perform, I pass the Java matcher objects as arguments. The test below fixes values that matter to the search assertion and checks the actual body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// src/test/kotlin/org/project/portfolio/article/ArticlesApiTest.kt (excerpt)
@Transactional
@DisplayName("Articles API integration tests")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class ArticlesApiTest(
    private val mockMvc: MockMvc,
    private val authService: AuthService,
    private val articleService: ArticleCommandService,
) : DescribeSpec({
    val userRegisterForm = UsersFixture.getRandomRegisterRequest()
    val author = authService.register(userRegisterForm)
    val authorToken = authService.login(userRegisterForm.email, userRegisterForm.password)

    describe("GET /api/v1/articles - List articles") {
        it("200 OK - filters results by keyword") {
            val uniqueKeyword = "UNIQUE_SEARCH_KEYWORD_999"
            articleService.createArticle(
                email = author.email,
                articleForm = ArticleForm(
                    title = "Title $uniqueKeyword",
                    content = "Body for the search test",
                    tags = listOf("kotlin", "spring"),
                ),
            )

            mockMvc.get("/api/v1/articles") {
                param("keyword", uniqueKeyword)
                contentType = MediaType.APPLICATION_JSON
            }.andExpectAll {
                status { isOk() }
                jsonPath("$.content.length()") { value(1) }
                jsonPath("$.content[0].title") { value("Title $uniqueKeyword") }
                jsonPath("$.content[0].tags[0]") { value("kotlin") }
            }
        }
    }

    describe("POST /api/v1/articles - Create an article") {
        it("201 Created - creates an article with images and tags") {
            val file = MockMultipartFile(
                "images", "image.jpg", "image/jpeg", "fake-image-content".toByteArray(),
            )

            mockMvc.perform(
                multipart("/api/v1/articles")
                    .file(file)
                    .param("title", "Test title")
                    .param("content", "Test body")
                    .param("tags", "spring", "kotlin")
                    .withJwt(authorToken)
                    .contentType(MediaType.MULTIPART_FORM_DATA),
            ).andExpectAll(
                status().isCreated,
                jsonPath("$.title").value("Test title"),
                jsonPath("$.tags[0]").value("spring"),
                jsonPath("$.tags[1]").value("kotlin"),
            )
        }
    }
})

Notification tests check that the response omits its receiver entity through doesNotExist(). They also confirm that the admin endpoint accepts a valid administrator request with 202 and rejects a disallowed user with 403.

1
2
3
4
5
6
7
8
9
10
// src/test/kotlin/org/project/portfolio/notification/NotificationsApiTest.kt (excerpt)
mockMvc.get("/api/v1/notifications") {
    withJwt(userToken)
}.andExpectAll {
    status { isOk() }
    content { contentType(MediaType.APPLICATION_JSON) }
    jsonPath("$.content[0].title") { value("Test notification") }
    jsonPath("$.content[0].receiverId") { value(user.id) }
    jsonPath("$.content[0].receiver") { doesNotExist() }
}

Temporarily make one expected status or value wrong when reviewing an unfamiliar DSL pattern. Confirm that the test fails for the expected assertion before trusting a green run.

Testing token rules outside the web layer

JwtProviderTest constructs JwtConfig and JwtProvider without booting Spring. This isolates the claim and decoder rules from HTTP routing and persistence. I check both directions of token-type separation so refresh credentials are rejected by the access decoder and access credentials are rejected by the refresh decoder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// src/test/kotlin/org/project/portfolio/auth/JwtProviderTest.kt (excerpt)
class JwtProviderTest :
    DescribeSpec({
        val jwtProperties = JwtProperties(
            secret = "test-secret-key-at-least-32-bytes-long-for-hs256",
            issuer = "test-issuer",
            accessExpiry = 3600,
            refreshExpiry = 604800,
        )
        val jwtConfig = JwtConfig(jwtProperties)
        val accessDecoder = jwtConfig.jwtDecoder()
        val refreshDecoder = jwtConfig.refreshJwtDecoder()
        val authConverter = jwtConfig.jwtAuthenticationConverter()
        val jwtProvider = JwtProvider(
            jwtProperties = jwtProperties,
            jwtEncoder = jwtConfig.jwtEncoder(),
            refreshJwtDecoder = refreshDecoder,
        )

        describe("Spring OAuth2 Resource Server JWT") {
            it("issues and verifies an access token and converts roles") {
                val token = jwtProvider.createAccessToken("user@test.com", setOf(UserRole.USER, UserRole.ADMIN))
                val jwt = accessDecoder.decode(token)
                val auth = authConverter.convert(jwt)!!

                jwt.subject shouldBe "user@test.com"
                auth.authorities.map { it.authority } shouldContainExactlyInAnyOrder listOf("ROLE_USER", "ROLE_ADMIN")
            }

            it("rejects a refresh token in the access decoder") {
                val refreshToken = jwtProvider.createRefreshToken("user@test.com", "refresh-jit-123")
                shouldThrow<JwtValidationException> { accessDecoder.decode(refreshToken) }
            }

            it("rejects an access token in the refresh decoder") {
                val accessToken = jwtProvider.createAccessToken("user@test.com", setOf(UserRole.USER))
                shouldThrow<UnauthorizedException> { jwtProvider.decodeRefreshToken(accessToken) }
            }

            it("rejects an expired access token") {
                val expiredToken = jwtProvider.createAccessToken(
                    email = "user@test.com",
                    roles = setOf(UserRole.USER),
                    issuedAt = Instant.now().minusSeconds(7200),
                    duration = 60,
                )
                shouldThrow<JwtValidationException> { accessDecoder.decode(expiredToken) }
            }
        }
    })

The provider accepts issuedAt and duration. Tests can issue a credential whose expiration is already well in the past. That removes both Thread.sleep and the risk of a test depending on clock scheduling just before a deadline.

Enforcing dependencies at build time

ArchUnit analyzes compiled classes, so it can find a dependency that package naming and code review miss. The domain rules prohibit dependencies on application, presentation, and infrastructure packages. A separate check stops the article domain from importing the notification domain directly. Their communication belongs behind events.

flowchart TD
    P["presentation / infrastructure"] --> A["application"]
    A --> D["Domain"]
    D -.->|"Reverse dependency blocked"| P
    ART["Article domain"] -.->|"Use events"| NOTI["Notification domain"]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/test/kotlin/org/project/portfolio/ArchitectureTest.kt
package org.project.portfolio

import com.tngtech.archunit.core.importer.ClassFileImporter
import com.tngtech.archunit.core.importer.ImportOption
import com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses
import io.kotest.core.spec.style.DescribeSpec

class ArchitectureTest :
    DescribeSpec({
        val classes = ClassFileImporter()
            .withImportOption(ImportOption.DoNotIncludeTests())
            .importPackages("org.project.portfolio")

        describe("Three-layer architecture dependencies") {
            it("domain packages cannot depend on application, presentation, or infrastructure") {
                noClasses()
                    .that().resideInAPackage("..domain..")
                    .should().dependOnClassesThat().resideInAnyPackage(
                        "..application..",
                        "..presentation..",
                        "..infrastructure..",
                    )
                    .allowEmptyShould(true)
                    .check(classes)
            }

            it("article communicates with notification through events") {
                noClasses()
                    .that().resideInAPackage("org.project.portfolio.article..")
                    .should().dependOnClassesThat().resideInAPackage("org.project.portfolio.notification..")
                    .check(classes)
            }
        }
    })

ImportOption.DoNotIncludeTests() restricts the rules to production classes. allowEmptyShould(true) lets an optional slice remain empty. Use that choice carefully where an unexpectedly empty import might also come from an incorrect package selector.

  • Make a search fixture that should match and a separate fixture that should not.
  • Force a wrong HTTP status and confirm the Kotlin matcher reports it.
  • Exercise expired tokens and wrong credential types in unit tests.
  • Keep architecture checks independent of Spring and run them in CI with the functional tests.
원티드 8월 프리온보딩 백엔드 챌린지 (게시글 CRUD). Contribute to cmsong111/Wanted-PreOnBoarding-Backend-Challenge development by creating an account on GitHub.
This post is licensed under CC BY 4.0 by the author.