【问题标题】:The test returns true, while it should return false and vice versa测试返回真,而它应该返回假,反之亦然
【发布时间】:2017-08-18 17:42:45
【问题描述】:

继续我的线程How to properly test a Spring Boot using Mockito。还有一个问题。

嗯,这个方法

@GetMapping("/checkUsernameAtRegistering")
public HttpEntity<Boolean> checkUsernameAtRegistering(@RequestParam String username) {
        return ResponseEntity.ok().body(!userService.existsByUsername(username));
}

在收到用户名并检查数据库后,如果用户名存在,则返回 false。 但是,测试

@Test
public void textExistsUsername() throws Exception {
    mockMvc
            .perform(get("/checkUserData/checkUsername")
            .param("username", "jonki97"))
            .andExpect(status().isOk())
            .andExpect(content().string("false"));
}

返回真。我有一个使用该用户名的用户,该方法应该返回 false。然而,事实并非如此。

java.lang.AssertionError: Response content 
Expected :false
Actual   :true

我觉得我理解语法很好

.andExpect(content().string("false"));

我期待一串假值。如何告诉服务返回什么?

【问题讨论】:

  • 您的样本对我“有效”。假设您的路径实际上是正确的(/checkUserData/checkUsername/checkUsernameAtRegistering)。请发帖minimal reproducible example
  • 在另一个论坛中,我得到了答案:“你在哪里设置了这个站点的设置来模拟返回 true? O_O 因为你把他关起来了,但没有任何期望。根本不起作用的奇迹,可能是 mockito defaults 给了一个很好的 moc,它在所有意外调用上都返回 null / 0 / false。但我不知道它是什么。
  • 我猜你的代码拆分器不适合。您明确声明期望为假,但显示的 AssertionError 显示“期望:真”。

标签: java spring spring-mvc spring-boot mockito


【解决方案1】:

您可以使用 Mockito 的 when 模拟服务的返回。

@Test
public void textExistsUsername() throws Exception {
    when(userService.existsByUsername("jonki97")).thenReturn(true);
    mockMvc
            .perform(get("/checkUserData/checkUsername")
            .param("username", "jonki97"))
            .andExpect(status().isOk())
            .andExpect(content().string("false"));
}

【讨论】:

  • 抱歉,这不起作用。继续同样的错误。 zapodaj.net/1db46416c9669.png.html
  • 我写错了,应该是when(userService.existsByUsername("jonki97")).thenReturn(true)
猜你喜欢
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-31
  • 2013-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多