Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowire MockMvc - Spring Data Rest

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!

like image 692
dardo Avatar asked Jan 02 '23 20:01

dardo


1 Answers

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.

like image 140
dardo Avatar answered Feb 27 '23 09:02

dardo