Reputation: 1478
I'm writing some tests in order to test my application. I'm using Spring Boot 2.0.2.
Image the following sitution with the following entity
@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;
... ...
}
and the following repository
@Repository
@RepositoryRestResource
public interface BoardRepository extends PagingAndSortingRepository<Board, Long> {}
Now the first step of the test that I want to do is to create a Board object, so my test starts with the following code
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();
});
}
}
The problem is that, the responseFromTestRestTemplate variable is filled with the usual spring data rest response. Instead inside the responseFromMockMvc variable, the body is empty.
I want to use the mockMvc solution only because is more effective from the tests point of view, but without the body is impossible to go on. The approach with the testRestTemplate was only an attemp to understand what's going on.
What I'm doing wrong? Thank you
Upvotes: 1
Views: 1322
Reputation: 22952
My guess is whatever your controller is doing or constraints on your entity, is preventing you from creating the same exact object twice.
Try the following changes:
Instead of:
Board b = new Board();
b.setName("gianni");
String responseFromTestRestTemplate = testRestTemplate.postForObject("/crud/boards", b, String.class);
Do:
Board b = new Board();
b.setName("gianni");
String responseFromTestRestTemplate = objectMapper.writeValueAsString(b);
The way you're only calling POST /crud/boards
once and that's via mockMvc
.
Upvotes: 1