Skip to content

Instantly share code, notes, and snippets.

@mike-seger
Last active November 3, 2024 14:11
Show Gist options
  • Select an option

  • Save mike-seger/60901af69057b1ae14a909353dafc38c to your computer and use it in GitHub Desktop.

Select an option

Save mike-seger/60901af69057b1ae14a909353dafc38c to your computer and use it in GitHub Desktop.
Parameterized controller tests
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.MethodSource
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.get
import java.util.stream.Stream
@SpringBootTest
@AutoConfigureMockMvc
class ControllerTests(@Autowired val mvc: MockMvc) {
companion object {
private val users = listOf("user1" to "password1", "user2" to "password2", "user3" to "password3")
@JvmStatic
fun userAndStatusProvider(expectedStatuses: List<HttpStatus>): Stream<Arguments> {
return users.zip(expectedStatuses) { (user, password), status ->
Arguments.of(user, password, status)
}.stream()
}
@JvmStatic
fun testCases(): Stream<Arguments> {
val statuses = listOf(HttpStatus.OK, HttpStatus.FORBIDDEN, HttpStatus.UNAUTHORIZED)
return userAndStatusProvider(statuses)
}
}
@ParameterizedTest
@MethodSource("userAndStatusProvider")
@DisplayName("Test various users and expected HTTP statuses")
fun `test various users with expected statuses`(user: String, password: String, expectedStatus: HttpStatus) {
mvc.get("/path/resource1") {
with(httpBasic(user, password))
accept(MediaType.APPLICATION_JSON)
}
.andDo { print() }
.andExpect {
status { isEqualTo(expectedStatus.value()) }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment