如何解决Spring Controller的JUnit AssertionError
我正在尝试测试REST控制器的GET / users端点。我正在使用Spring Boot和Mongodb。
我的控制器:
class MessageController(
private val userRepository: UserRepository
) {
@GetMapping("/users")
fun getUsers(@RequestParam(value = "name",required = false) name: String?): ResponseEntity<List<User>> {
val users: List<User> =
name?.takeIf { it.isNotEmpty() }?.let { userRepository.findUsersByName(it) } ?: userRepository.findAll()
return ResponseEntity.ok(users)
}
我的测试:
@Test
fun shouldReturnUsers() {
val users = listOf(User("1","James",18))
val response = restTemplate.getForEntity<List<User>>("/users")
given(userRepository.findAll()).willReturn(users)
val response = restTemplate.getForEntity<List<User>>("/users")
assertThat(response.statusCode).isEqualTo(HttpStatus.OK)
assertThat(response.body).containsExactlyInAnyOrderElementsOf(users)
}
我的最后一个断言给我一个错误:
java.lang.AssertionError:
Expecting:
<[{"age"=18,"id"="1","name"="James"}]>
to contain exactly in any order:
<[User(id=1,name=James,age=18)]>
elements not found:
<[User(id=1,age=18)]>
and elements not expected:
<[{"age"=18,"name"="James"}]>
为什么我的response.body按字母顺序排序? 我怎么能通过考试?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。