Inject mock into Spring MockMvc WebApplicationContext

前端 未结 3 627
终归单人心
终归单人心 2021-01-31 22:00

I\'m working to test (via JUnit4 and Spring MockMvc) a REST service adapter using Spring-boot. The adapter simply passes along requests made to it, to another REST service (usin

3条回答
  •  旧巷少年郎
    2021-01-31 22:38

    Spring's MockRestServiceServer is exactly what you're looking for.

    Short description from javadoc of the class:

    Main entry point for client-side REST testing. Used for tests that involve direct or indirect (through client code) use of the RestTemplate. Provides a way to set up fine-grained expectations on the requests that will be performed through the RestTemplate and a way to define the responses to send back removing the need for an actual running server.

    Try to set up your test like this:

    @WebAppConfiguration
    @ContextConfiguration(classes = {YourSpringConfig.class})
    @RunWith(SpringJUnit4ClassRunner.class)
    public class ExampleResourceTest {
    
        private MockMvc mockMvc;
        private MockRestServiceServer mockRestServiceServer;
    
        @Autowired
        private WebApplicationContext wac;
    
        @Autowired
        private RestOperations restOperations;
    
        @Before
        public void setUp() throws Exception {
            mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
            mockRestServiceServer = MockRestServiceServer.createServer((RestTemplate) restOperations);
        }
    
    
        @Test
        public void testMyApiCall() throws Exception {
            // Following line verifies that our code behind /api/my/endpoint made a REST PUT
            // with expected parameters to remote service successfully
            expectRestCallSuccess();
    
            this.mockMvc.perform(MockMvcRequestBuilders.get("/api/my/endpoint"))
                .andExpect(status().isOk());
        }
    
        private void expectRestCallSuccess() {
            mockRestServiceServer.expect(
                requestTo("http://remote.rest.service/api/resource"))
                .andExpect(method(PUT))
                .andRespond(withSuccess("{\"message\": \"hello\"}", APPLICATION_JSON));
        }
    
    
    }
    

提交回复
热议问题