spring/SpringBoot
(Spring Boot)TestRestTemplate null request Error
ri5
2021. 7. 12. 19:55
TestCode
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@Transactional
public class GamesApiControllerTest extends TestCase {
@Autowired
private TestRestTemplate restTemplate;
@LocalServerPort
private int port;
@Test
public void testGamesReResponse() {
Integer request = 1;
String url = "http://localhost:"+port+"/api/appendGames";
//when
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseEntity.getBody().toJSONString()).contains("games");
}
}
api
@PostMapping("api/appendGames")
public Map<String,List<GameLimitTagListResponseDto>> gamesReResponse (Integer page){
HashMap<String,List<GameLimitTagListResponseDto>> map = new HashMap<>();
map.put("games",gamesService.findAllPaging(page));
return map;
}
error
java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "page" is null
디버깅
restTempate에서 body에서 데이터를 담아 api를 요청하지만 @requestBody를 선언 해주지 않아서 자바객체로 받지못해서 계속 page에 null로 값이 들어 감.

※ @RequestParam은 url을 통해 데이터를 받아오기 때문에 @RequestBody를 사용.
수정후
@PostMapping("api/appendGames")
public Map<String,List<GameLimitTagListResponseDto>> gamesReResponse (@RequestBody Integer page){
HashMap<String,List<GameLimitTagListResponseDto>> map = new HashMap<>();
map.put("games",gamesService.findAllPaging(page));
return map;
}