Overriding beans in Integration tests

后端 未结 7 1794
眼角桃花
眼角桃花 2020-12-23 09:16

For my Spring-Boot app I provide a RestTemplate though a @Configuration file so I can add sensible defaults(ex Timeouts). For my integration tests I would like to mock the R

相关标签:
7条回答
  • 2020-12-23 09:51

    1. You can use @Primary annotation:

    @Configuration
    public class MockRestTemplateConfiguration {
    
        @Bean
        @Primary
        public RestTemplate restTemplate() {
            return Mockito.mock(RestTemplate.class)
        }
    }
    

    BTW, I wrote blog post about faking Spring bean

    2. But I would suggest to take a look at Spring RestTemplate testing support. This would be simple example:

      private MockRestServiceServer mockServer;
    
      @Autowired
      private RestTemplate restTemplate;
    
      @Autowired
      private UsersClient usersClient;
    
      @BeforeMethod
      public void init() {
        mockServer = MockRestServiceServer.createServer(restTemplate);
      }
    
      @Test
      public void testSingleGet() throws Exception {
        // GIVEN
        int testingIdentifier = 0;
        mockServer.expect(requestTo(USERS_URL + "/" + testingIdentifier))
          .andExpect(method(HttpMethod.GET))
          .andRespond(withSuccess(TEST_RECORD0, MediaType.APPLICATION_JSON));
    
    
        // WHEN
        User user = usersClient.getUser(testingIdentifier);
    
        // THEN
        mockServer.verify();
        assertEquals(user.getName(), USER0_NAME);
        assertEquals(user.getEmail(), USER0_EMAIL);
      }
    

    More examples can be found in my Github repo here

    0 讨论(0)
提交回复
热议问题