【发布时间】:2018-11-19 20:21:57
【问题描述】:
我正在编写一些测试来测试我的应用程序。我正在使用 Spring Boot 2.0.2。
将以下情况与 以下实体
@Entity
public class Board extends BaseEntity {
@Column(length = 128)
@NotNull
private String name;
@OneToMany(cascade = CascadeType.REMOVE, orphanRemoval = true, mappedBy = "board")
private Set<Activity> activities;
... ...
}
以及以下存储库
@Repository
@RepositoryRestResource
public interface BoardRepository extends PagingAndSortingRepository<Board, Long> {}
现在我要做的测试的第一步是创建一个 Board 对象,所以我的测试从以下代码开始
import static org.junit.Assert.assertNotNull;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class BoardControllerRestIT {
@Autowired
private TestRestTemplate testRestTemplate;
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testBoardCreation() throws Exception {
Board b = new Board();
b.setName("gianni");
String responseFromTestRestTemplate = testRestTemplate.postForObject("/crud/boards", b, String.class);
assertNotNull(responseFromTestRestTemplate);
ResultActions resultActions = mockMvc.perform(
post("/crud/boards")
.content(objectMapper.writeValueAsString(b))
.contentType(MediaType.APPLICATION_JSON));
resultActions.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
resultActions.andDo(mvcResult -> {
String responseFromMockMvc = mvcResult.getResponse().getContentAsString();
});
}
}
问题是,responseFromTestRestTemplate 变量填充了通常的弹簧数据休息响应。 而在 responseFromMockMvc 变量中,主体是空的。
我想使用mockMvc解决方案只是因为从测试的角度来看更有效,但是没有body是不可能继续下去的。 使用 testRestTemplate 的方法只是尝试了解正在发生的事情。
我做错了什么? 谢谢
【问题讨论】:
标签: spring spring-mvc spring-boot spring-data spring-data-rest