https://kotlinlang.org logo
#kotest
Title
# kotest
j

John Fletcher

09/25/2023, 7:33 PM
Is there a way to use Spring Security-based annotations on Kotest tests?
l

LeoColman

09/25/2023, 8:11 PM
should work the same way as junit's injection
j

John Fletcher

09/26/2023, 5:14 AM
OK. My IDE complains "This annotation is not applicable to target 'expression'".
l

LeoColman

09/26/2023, 2:14 PM
Could you show us an example on how you are setting the test up?
j

John Fletcher

09/27/2023, 5:55 AM
I built an example. I can upload the repo to github if it helps.
Copy code
package org.springframework.security.samples

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers

@ExtendWith(SpringExtension::class)
@SpringBootTest
@AutoConfigureMockMvc
class KotestSecurity( mockMvc: MockMvc) : StringSpec({

    @WithMockUser
    "dont need login" {
        val mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/index"))
            .andExpect(MockMvcResultMatchers.status().isOk())
    }

    "need login" {
        val mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/user/index"))
            .andExpect(MockMvcResultMatchers.status().is3xxRedirection())
            .andReturn()
    }
})
l

LeoColman

09/27/2023, 1:36 PM
I believe
@WithMockUser
should go on the class instead of the test function
Like the last example on this article
j

John Fletcher

09/27/2023, 1:54 PM
That works as a workaround. In the example, the second test fails, because it should test the scenario of not being logged in. But as a workaround you could split your tests into more separate classes.
👍 1
l

LeoColman

09/27/2023, 1:56 PM
I see
I don't see a way to currently apply that condition only to a single test in the same way
By using the annotation, I mean. Perhaps we can raise an issue for this
But this is probably on Spring's side to solve
j

John Fletcher

09/27/2023, 2:37 PM
If I am using a custom Spring-derived annotation, could that work?
4 Views