【问题标题】:RestTemplate exception no converters found while testing a Spring boot Application测试 Spring 启动应用程序时未找到 RestTemplate 异常
【发布时间】:2019-09-24 03:50:00
【问题描述】:

我是 Spring Boot 应用程序测试领域的新手。 我想对我的 Spring Boot 应用程序进行集成测试。但我得到以下异常。

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

我正在将员工和部门添加到具有双向关系的内存数据库中。

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());            

}

这是我的新编辑。根据前面提到的建议,我试图实现所有这些,但都没有成功。它给出了错误的请求 400 空异常。请建议我如何解决它

【问题讨论】:

  • 如果您使用的是 Spring Boot,请自动连接您的 RestTemplate 实例,而不是使用 new;你会得到一个具有自动配置转换器等的。
  • 仍然显示相同的异常..!
  • 我看了。但也没有解决。我已经更新了代码。请看一下
  • 将标题更改为 MediaType.APPLICATION_JSON 并尝试应该可以工作的 @VanditShah

标签: java spring spring-boot junit mockito


【解决方案1】:

您应该将 ContentType 从 APPLICATION_FORM_URLENCODED 更改为 APPLICATION_JSON

httpHeaders.setContentType(MediaType.APPLICATION_JSON);

还需要添加 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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2013-04-18
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多