我正在编写一些测试来测试我的应用程序 . 我正在使用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变量填充了通常的spring数据rest响应 . 而是在responseFromMockMvc变量中,正文是空的 .
我想使用mockMvc解决方案只是因为从测试的角度来看更有效,但没有身体是不可能继续下去的 . 使用testRestTemplate的方法只是尝试了解正在发生的事情 .
我做错了什么?谢谢
1 回答
我的猜测是你的控制器正在做什么或你的实体的约束,阻止你两次创建相同的确切对象 .
请尝试以下更改:
代替:
做:
这种方式你只需要调用
POST /crud/boards
一次,那就是mockMvc
.