JUnit测试JSON响应时的AssertionError

时间:2018-01-10 15:14:56

标签: java json spring junit

我正在创建我的第一个单元测试,并且只是想根据一个Spring教程创建一些非常简单的东西。

以下是我遇到的错误:

java.lang.AssertionError: Response content
Expected: (null or an empty string)
 but: was "Debug"

我的控制器:

@RestController
@RequestMapping(value = "/person")
public class PersonController {

  @Autowired
  protected PersonService personService;

  @RequestMapping(value = "/lastName", produces = "application/json")
  public String lastName(@RequestParam(value = "cid") String cid)
  {
    return personService.findByCId(cid).getLastName();
  }

我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MvcLastNameTest {

@Autowired
  private MockMvc mockMvc;

  @Test
  public void shouldReturnNonNullString() throws Exception {
    this.mockMvc.perform(get("/person/lastName?cid=123456")).andDo(print()).andExpect(status().isOk())
        .andExpect(content().string(isEmptyOrNullString()));
  }

}

1 个答案:

答案 0 :(得分:2)

在您的测试中,您期待EmptyOrNullString,但您的控制器会产生lastName

改变你的期望:

.andExpect(content().string("Debug")); // or any other valid lastName