Java中Service / Rest方法的集成测试

时间:2018-06-08 12:12:01

标签: java spring-boot integration-testing

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

这是我人生中的第一次考验。

我需要我的集成测试调用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

1 个答案:

答案 0 :(得分:0)

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

当您想要进行Integrations测试时,您必须实际调用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