2

I want to test a Tasklet implementation which uses an @Autowired RestTemplateBuilder to build a RestTemplate. The RestTemplate executes a request. I want to mock the response of this request.

@ContextConfiguration(classes = DogTasklet.class )
@RunWith(SpringRunner.class)
public class DogTaskletTest {

    @MockBean
    RestTemplateBuilder restTemplateBuilder;
    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private Tasklet sut;

    @Before
    public void setUp() throws Exception {
        given(this.restTemplateBuilder.build()).willReturn(restTemplate);
    }
}

The given() statement throws a NPE because the RestTemplateBuilder instance is null. What have I missed?

Update: I changed the test to the following which solves the NPE, now I have null ResponseEntity during sut.execute().

@RunWith(SpringRunner.class)
public class DogTaskletTest {

@TestConfiguration
static class TestConfig {

    @Bean
    RestTemplateBuilder restTemplateBuilder() {
        RestTemplateBuilder restTemplateBuilder = mock(RestTemplateBuilder.class);
        RestTemplate restTemplate = mock(RestTemplate.class);
        ResponseEntity responseEntity = mock(ResponseEntity.class);

        given(restTemplateBuilder.build()).willReturn(restTemplate);
        given(restTemplate.execute(any(), any(), any(), any())).willReturn(responseEntity);
        given(responseEntity.getBody()).willReturn("{}");

        return restTemplateBuilder;
    }

    @Bean
    DogTasklet sut() {
        return new DogTasklet("string", restTemplateBuilder());
    }
}
    @Test
    public void execute() throws Exception {
        // when
        sut.execute(stepContribution, chunkContext);
    }
}
yN.
  • 1,847
  • 5
  • 30
  • 47
  • 1
    Have you seen this? https://stackoverflow.com/questions/49128616/mocking-resttemplatebuilder-and-resttemplate-in-spring-integration-test – Urosh T. Aug 29 '18 at 07:24
  • 1
    Are you sure that you are calling the correct `restTemplate#execute` method? Because that method is overloaded quite a bit and it could be that your `when` doesn't work because your are calling the wrong method. – Urosh T. Aug 29 '18 at 10:35
  • Thank you so much! In fact I wasnt even using execute() but exchange()... – yN. Aug 30 '18 at 07:15
  • Yes, `exchange`, I got confused there, sorry :) Glad you got it working. Cheers! – Urosh T. Aug 30 '18 at 07:25

1 Answers1

0

Thanks to Urosh I figured out that I was mocking the wrong method in my given() statement. Therefore it did not return the mocked RestTemplate.

I changed the given() to:

        given(restTemplate.exchange(
            anyString(),
            eq(HttpMethod.GET),
            any(HttpEntity.class),
            eq(String.class)
        )).willReturn(responseEntity);
yN.
  • 1,847
  • 5
  • 30
  • 47