【问题标题】:Integration test for Service/Rest methods in JavaJava中Service/Rest方法的集成测试
【发布时间】:2018-11-18 12:01:03
【问题描述】:

正如我在标题中提到的,我需要创建集成测试。

这是我人生中的第一次测试。

我需要我的集成测试调用一个 rest 方法,但我收到了这个错误:

这是我的测试:

 @SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = CrewApplication.class)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:TeamController")
public class TeamIntegrationTest {

    @Autowired
    MockMvc mockMvc;

    @Test
    public void integrationTeamTest() throws Exception {
        MvcResult mvcResult = mockMvc.perform(
                MockMvcRequestBuilders.get("/teams")
                .accept(MediaType.APPLICATION_JSON)
        ).andReturn();

        System.out.println(mvcResult.getResponse());
    }
}

这是我的休息方法:

@RestController
public class TeamController {

    private final TeamService teamService;
    private final PersonService personService;

    @Autowired
    public TeamController(TeamService teamService, PersonService personService) {
        this.teamService = teamService;
        this.personService = personService;
    }

    @GetMapping("/teams")
    public List<TeamDto> findAll() {
        return teamService.findAll();
    }

方法工作,Junit 测试工作只有这个集成抛出错误:

java.lang.NullPointerException

【问题讨论】:

    标签: java spring-boot integration-testing


    【解决方案1】:

    您正在混合使用 Spring 单元测试和 Spring 集成测试。

    当您想要进行集成测试时,您必须实际调用 API。

    @RunWith(SpringRunner.class)
    @SpringBootTest(
            webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    classes = CrewApplication.class)
    
    public class TeamIntegrationTest {
    
        @Autowired
        private TestRestTemplate restTemplate;
    
        @Test
        public void integrationTeamTest() throws Exception {
            String body = this.restTemplate.getForObject("/teams", String.class);
    
            assertThat(body).isEqualTo("TEAM REPRESENTATION AS STRING");
        }
    }
    

    如果您需要更多信息,请访问Spring Documentation

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2021-07-27
      • 1970-01-01
      相关资源
      最近更新 更多