Vandit Shah
Vandit Shah

Reputation: 115

RestTemplate exception no converters found while testing a Spring boot Application

I am new to testing world of spring boot application. I want to do an integration testing on my Spring boot application. But i am getting following exception.

org.springframework.web.client.HttpClientErrorException$BadRequest: 400 null

I am adding an employee and department into the in-memory database with bi-directional relationship.

public void testPostEmployee() throws Exception
            {       
        System.out.println("Inside Post Employee method");

        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        EmployeeTestDTO employeeTestDTO = new EmployeeTestDTO();
        DepartmentTest departmentTest = new DepartmentTest(1,"Sales");
        employeeTestDTO.setName("ABC");
        employeeTestDTO.setAge(20);
        employeeTestDTO.setSalary(1200.1);
        employeeTestDTO.setDepartmentTest(departmentTest);

        ObjectMapper objectMapper = new ObjectMapper();

        String data = objectMapper.writeValueAsString(employeeTestDTO);
        System.out.println(data);

        HttpEntity<String> httpEntity = new HttpEntity<String>(data,httpHeaders);

        ResponseEntity<?> postResponse = restTemplate.postForEntity(createURLWithPort("/employee"), 
                httpEntity,String.class);

        Assert.assertEquals(201, postResponse.getStatusCodeValue());            

}

This is my new edit. As per previously stated suggestion i tried to implement all of them but neither of them succeded. It gives the bad request 400 null exception. Please suggest me how to solve it

Upvotes: 0

Views: 201

Answers (1)

i.bondarenko
i.bondarenko

Reputation: 3572

You should change ContentType from APPLICATION_FORM_URLENCODED to APPLICATION_JSON.

httpHeaders.setContentType(MediaType.APPLICATION_JSON);

Also you need to add RestController:

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
public class Controller {

    @PostMapping("/employee")
    @ResponseStatus(HttpStatus.CREATED)
    public void getEmploee(@RequestBody EmployeeTestDTO employee) {
        System.out.println(employee);
    }
}

Upvotes: 1

Related Questions