【问题标题】:how can i create unit test with not found exception?如何创建未发现异常的单元测试?
【发布时间】:2020-07-15 03:10:48
【问题描述】:

这里我有一个测试来测试控制器,我成功地测试了 create 和 findByName,我想用 findByName_notFound 添​​加测试,但我还不明白怎么做。

这是我的代码:

@Test
public void shouldRegisterNewStudent() throws Exception {
    Student student = new Student();
    student.setId(1);
    student.setParentsName("farizan");
    student.setParentsMobile("8465");
    student.setName("sahru");
    student.setClassroom(null);
    student.setNote("free text");
    Mockito.when(studentService.save(student)).thenReturn(student);

    mockMvc.perform(post("/register")
            .contentType("application/json")
            .content(objectMapper.writeValueAsString(student)))
            .andExpect(status().isCreated());
}
@Test
public void findStudentByName()throws Exception{
    Student student = new Student();
    student.setId(1);
    student.setParentsName("farizan");
    student.setParentsMobile("8465");
    student.setName("sahru");
    student.setClassroom(null);
    student.setNote("free text");
    final String name = "sahru";
    given(studentService.findByName("sahru")).willReturn(student);
    mockMvc.perform(get("/findByName/{name}",name)
            .contentType("application/json")
            .content(objectMapper.writeValueAsString(student)))
            .andExpect(status().isOk());
}
@Test
public void findStudentByName_notFound()throws Exception{
    final String name = "sahru";
    given(studentService.findByName("sarah")).willReturn((Student) Collections.emptyList());
    mockMvc.perform(get("/findByName/{name}",name)
            .contentType("application/json"))
            .andExpect(status().isNotFound());
}

}

【问题讨论】:

    标签: spring-boot unit-testing testing controller


    【解决方案1】:

    【讨论】:

    • 这不是答案;相反,它会更好地作为对 OP 问题的评论。
    【解决方案2】:

    您可以使用rest-assured库来测试rest API,它易于使用且功能强大。

    步骤:

    1. 在您的构建工具中包含依赖项,使用 maven 之类的:

           <dependency>
              <groupId>io.rest-assured</groupId>
              <artifactId>rest-assured</artifactId>
              <version>3.0.5</version>
              <scope>test</scope>
          </dependency>
      
    2. 如下创建springboot测试:

      
      @LocalServerPort
      private int port;
      
      @Test
      public void test() {
          RestAssured.given()
                  .port(port)
                  .get("/test/api") //your endpoint
                  .then()
                  .assertThat()
                  .statusCode(HttpStatus.NOT_FOUND.value());
       }
      }
      

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2012-03-14
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 2020-01-13
      相关资源
      最近更新 更多