用Mockito 2模拟通用RestTemplate将参数存为null或空字符串

时间:2018-11-11 23:46:16

标签: java spring junit mockito resttemplate

这是我的存根代码。使用适当的参数(显示在存根代码下方)调用交换方法,但是由于某种原因,when().then()语句正在寻找空参数。为什么在这里抛出PotentialStubbingProblem异常?

@BeforeEach
public <T> void configureMocks() {
    when(apiAccess.getKey()).thenReturn("abcdefghijklmnopqrstuvwxyz");
    when(apiAccess.getUrlPrefix()).thenReturn("{region}.api.riotgames.com");
    val response = new ResponseEntity<Collection<T>>(HttpStatus.OK);
    when(restTemplate.exchange(ArgumentMatchers.anyString(),
            ArgumentMatchers.any(HttpMethod.class),
            (HttpEntity<?>) isNull(),
            eq(new ParameterizedTypeReference<Collection<T>>() {})))
            .thenReturn(response);
}

PotentialStubbingProblem输出如下所示:

org.mockito.exceptions.misusing.PotentialStubbingProblem: 
Strict stubbing argument mismatch. Please check:
 - this invocation of 'exchange' method:
    restTemplate.exchange(
    https://JP1.api.riotgames.com/lol/champion-mastery/v3/champion-masteries/by-summoner/1234567890?api_key=abcdefghijklmnopqrstuvwxyz,
    GET,
    null,
    ParameterizedTypeReference<java.util.Collection<T>>
);
    -> at org.eyeoftheherald.riotapiinterface.service.RiotApiService.getEntityList(RiotApiService.java:176)
 - has following stubbing(s) with different arguments:
    1. restTemplate.exchange("", null, null, null);

ApiAccess如下所示:

@Configuration
public class RiotApiInterfaceConfiguration {
    @Getter
    @Setter
    @Configuration
    @PropertySource("classpath:configuration.properties")
    @ConfigurationProperties(prefix = "api-access")
    public static class ApiAccess {
        private String key;
        private String urlPrefix;
    }

    @Autowired
    public RiotApiInterfaceConfiguration() {
    }

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

0 个答案:

没有答案