Given the Repository
public interface ResourceRepository extends CrudRepository<Resource, Long> { ... }
The following test code:
@WebMvcTest
@RunWith(SpringRunner.class)
public class RestResourceTests {
@Autowired
private MockMvc mockMvc;
@Test
public void create_ValidResource_Should201() {
String requestJson = "...";
mockMvc.perform(
post("/resource")
.content(requestJson)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isCreated()); // This fails with 404
}
}
In order to fix the issue, I need to inject the WebApplicationContext
and manually create the MockMvc
object as follows:
@SpringBootTest
@RunWith(SpringRunner.class)
public class RestResourceTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
this.mockMvc = webAppContextSetup(webApplicationContext).build();
}
Is there a simpler way to achieve this?
Thanks!