Inject mock into Spring MockMvc WebApplicationContext

前端 未结 3 628
终归单人心
终归单人心 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条回答
  •  旧时难觅i
    2021-01-31 22:34

    Here's another solution. Simply put, it just creates a new RestTemplate bean and overrides the one already registered.

    So while it performs produces the same functionality as @mzc answer, it allows me to use Mockito to craft the response and verification matchers a bit easier.

    Not that it's more than a couple lines of code, but it also prevents from having to add additional code to convert from the Response object to a string for the above mockRestServiceServer.expect().andRespond() method's arg.

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @SpringApplicationConfiguration(classes = MainSpringBootAdapter.class)
    @TestPropertySource("/application-junit.properties")
    public class WacControllerTest {
    
        private static String Controller_URL = Constants.REQUEST_MAPPING_PATH + Constants.REQUEST_MAPPING_RESOURCE + compressedParams_all;
    
        @Configuration
            static class Config {
                @Bean
                @Primary
                public RestTemplate restTemplateMock() {
                    return Mockito.mock(RestTemplate.class);
            }
        }
    
        @Autowired
        private WebApplicationContext wac;
    
        private MockMvc mockMvc;
    
        @InjectMocks
        private Controller Controller;
    
        @Mock
        private RestTemplate rt;
    
        @Value("${file}")
        private String file;
    
        @Spy
        private DataProvider dp;
    
        @Before
        public void setup() throws Exception {
            dp = new DataProvider(file); 
    
            MockitoAnnotations.initMocks(this);
            this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
            this.rt = (RestTemplate) this.wac.getBean("restTemplateMock");
        }
    
        @Test
        public void testGetResponse() throws Exception {
    
            String[] strings = {"request", "100"};
    
            //Set the request params from the client request
            Map parameters = new HashMap();
            parameters.put(Constants.PARAM_SINGLELINE, strings[0]);
            parameters.put(Constants.PARAM_FORMAT, Constants.PARAMS_FORMAT.JSON);
    
            Mockito.when(
                rt.getForObject(Mockito. any(), Mockito.> any(), Mockito.> any()))
                .thenReturn(populateTestResponse());
    
            mockMvc.perform(get(Controller_URL, strings)
                .accept(Constants.APPLICATION_JSON_UTF8))
                .andDo(MockMvcResultHandlers.print());
    
            Mockito.verify(rt, Mockito.times(1)).getForObject(Mockito. any(), Mockito.> any(), Mockito.> any());
    
            }
    
    
            private Response populateTestResponse() {
                Response  resp = new Response();
    
                resp.setScore(new BigDecimal(100));
                resp.setData("Some Data");
    
                return resp;
        }
    }
    

提交回复
热议问题