正在验证Kotlin控制器中的Spring@PathVariable



我正在尝试验证Kotlin Spring控制器内的String@PathVariable

@RestController
@Validated
@RequestMapping("/kotlin/")
open class KStringController {
@GetMapping(path = ["string/{username}"],
produces = [APPLICATION_JSON_VALUE])
@ResponseBody
fun validateStringPathVariable(
@Pattern(regexp = "[A-Za-z]+", message = "Username Pattern Validation Message")
@Size(min = 2, max = 15, message = "Username Size Validation Message")
@PathVariable("username") username: String?
): ResponseEntity<String>? {
logger.info { String.format("validateStringPathVariable: Got Username [%s]", username) }
System.out.printf("validateStringPathVariable: Username is [%s]%n", username)
return ResponseEntity.ok("Username is valid")
}
}

我有它的单元测试:

@ExtendWith(SpringExtension::class)
@WebMvcTest(KStringController::class)
@AutoConfigureMockMvc
class KStringGetControllerTest {
@field:Autowired
private lateinit var mvc: MockMvc
@Test
@Throws(Exception::class)
fun validStringPathVariable() {
val request: MockHttpServletRequestBuilder = givenARequestFor("/kotlin/string/mike")
val actions: ResultActions = whenTheRequestIsMade(request)
thenExpect(actions,
MockMvcResultMatchers.status().isOk,
MockMvcResultMatchers.content().bytes("Username is valid".toByteArray()))
}
@Test
@Throws(Exception::class)
fun shoutsWhenStringPathVariableIsTooShort() {
val request = givenARequestFor("/kotlin/string/a")
val actions = whenTheRequestIsMade(request)
val response = """{
"validationErrors": [
{
"fieldName": "validateStringPathVariable.username",
"message": "Username Size Validation Message"
}
]
}"""
val content = MockMvcResultMatchers.content()
thenExpect(actions,
MockMvcResultMatchers.status().isBadRequest,
content.contentType(MediaType.APPLICATION_JSON),
content.json(response))
}
private fun givenARequestFor(url: String): MockHttpServletRequestBuilder {
return MockMvcRequestBuilders.get(url)
.characterEncoding("UTF-8")
}
@Throws(Exception::class)
private fun whenTheRequestIsMade(request: MockHttpServletRequestBuilder): ResultActions {
return mvc.perform(request)
}
@Throws(Exception::class)
private fun thenExpect(resultActions: ResultActions, vararg matchers: ResultMatcher) {
resultActions.andExpect(ResultMatcher.matchAll(*matchers))
}

目前第二次测试失败;当我期望400时,它返回200响应代码。在https://github.com/Mavelous/spring-validation.

在其他人的帮助下,我设法找到了一个解决方案。

快速回答:将函数更改为open fun validateStringPathVariable,验证将开始工作。

备选答案:在build.gradle文件中使用org.jetbrains.kotlin.plugin.spring插件。

我还创建了一篇博客文章,其中有更长的描述:http://mavelo.us/2021/04/07/spring-validation-in-kotlin.html

相关内容

  • 没有找到相关文章

最新更新