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!
I figured out a "clean" solution, but it feels like a bug to me.
@SpringBootTest
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc // <-- this is the fix
public class RestResourceTests {
@Autowired
private MockMvc mockMvc; // <-- now injects with repositories wired.
The reason I feel like this is a bug, the @WebMvcTest
annotation already places the @AutoConfigureMockMvc
annotation on the class under test.
It feels like @WebMvcTest
isn't looking at the web components loaded with @RestRepository
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With