春季启动:MockMvc返回空的身体为POST请求

时间:2019-11-27 18:09:36

标签: java spring spring-boot spring-data-rest

我正在用Spring Boot和Spring Data Rest编写一个小型演示应用程序。我有以下模型和相应的存储库:

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    private String jobTitle;

    public Employee() {
    }

    ... // getters and setters
}
@RepositoryRestResource(collectionResourceRel = "employees", path = "employees")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {
    @RestResource(path = "by-last-name", rel = "by-last-name")
    Page<Employee> findByLastNameIgnoreCase(Pageable pageable, @Param("lastName") String lastName);

    @RestResource(path = "by-job-title", rel = "by-job-title")
    Page<Employee> findByJobTitleIgnoreCase(Pageable pageable, @Param("jobTitle") String jobTitle);
}

如果我通过邮递员发出以下请求:

POST localhost:8080/employees
{"firstName":"Test","lastName":"McTest","jobTitle":"Tester"}

我收到了有关我新创建的实体的完整回复正文:

{
  "firstName": "Test",
  "lastName": "McTest",
  "jobTitle": "Tester",
  "_links": {
    "self": {
      "href": "http://localhost:8080/employees/120"
    },
    "employee": {
      "href": "http://localhost:8080/employees/120"
    }
  }
}

但是,当我通过如下所示的测试提出相同的请求时,我得到一个空的响应正文:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class)
@AutoConfigureMockMvc
public class EmployeeIntegrationTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    ObjectMapper objectMapper;

    @Test
    public void testAddEmployee() throws Exception {
        Employee employee = new Employee();
        employee.setFirstName("Test");
        employee.setLastName("McTest");
        employee.setJobTitle("Tester");

        MockHttpServletRequestBuilder requestBuilder = post("/employees")
                .contentType(APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(employee));

        mvc
                .perform(requestBuilder)
                .andExpect(status().isCreated())
                .andExpect(jsonPath("$.firstName", Matchers.is("Test"))); // Fails, because content is empty. 
    }
}

对于它的价值,如果我随后在测试中执行GET /employees,实际上我确实在响应正文中看到了该实体,因此我知道它是被创建的。

我的期望是通过这两种方法我都将得到相同的响应,可惜目前情况并非如此,似乎POST的{​​{1}}请求没有返回正文。我是否可能在某处缺少配置设置?

1 个答案:

答案 0 :(得分:0)

我能够通过显式设置来解决该问题

@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.setReturnBodyForPutAndPost(true);
}

在实现@Configuration的{​​{1}}类内部

我的猜测是,这是对主代码隐式设置的,而不是针对测试的。