使用@MockBean模拟的RestTemplateBuilder为null

时间:2018-08-29 06:38:03

标签: java spring unit-testing mockito bdd

我想测试一个$arrays=[ ["name" => "Khv","emails" => [0 => ["email" => "demo1@yahoo.com"] ] ], ["name" => "asy", "emails" => [0 => ["email" => "demo2@yahoo.com"] ] ] ]; $emails=collect(); foreach ($arrays as $array) { $emails->push($array['emails'][0]['email']); } dd($emails); 实现,该实现使用Tasklet @Autowired来构建RestTemplateBuilderRestTemplate执行一个请求。我想模拟此请求的响应。

RestTemplate

由于@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); } } 实例为given(),因此RestTemplateBuilder语句将引发NPE。我错过了什么?

更新:我将测试更改为以下解决NPE的方法,现在在null中有null ResponseEntity

sut.execute()

1 个答案:

答案 0 :(得分:0)

感谢Urosh,我发现自己在given()语句中嘲笑了错误的方法。因此,它没有返回模拟的RestTemplate

我将given()更改为:

        given(restTemplate.exchange(
            anyString(),
            eq(HttpMethod.GET),
            any(HttpEntity.class),
            eq(String.class)
        )).willReturn(responseEntity);