参数字符串的匹配器。类,字节[]。类Junit

参数字符串的匹配器。类,字节[]。类Junit,junit,mockito,Junit,Mockito,我有一个类似于mRestAccess.exchange的代码(url,HttpMethod.GET,request,byte[].class)现在我想用JUnit测试一下 当我编写Mockito.doReturn(stringResponse).When(mRestAccess).exchange(Mockito.anyString(),Mockito.any(HttpMethod.class),Mockito.any(HttpEntity.class),??) 写什么来代替?使用下面的语句使用

我有一个类似于
mRestAccess.exchange的代码(url,HttpMethod.GET,request,byte[].class)现在我想用JUnit测试一下

当我编写
Mockito.doReturn(stringResponse).When(mRestAccess).exchange(Mockito.anyString(),Mockito.any(HttpMethod.class),Mockito.any(HttpEntity.class),??)


写什么来代替?

使用下面的语句使用powermockito模拟spring restTemplate

PowerMockito.when(restTemplate.exchange(
     Matchers.anyString(), 
     Matchers.any(HttpMethod.class),
     Matchers.<HttpEntity<?>> any(),
     Matchers.any(Class.class)))
 .thenReturn(respEntity);
PowerMockito.when(restemplate.exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),

匹配器。您可以使用
Mockito.eq
来测试参数的相等性(使用
equals
)。为了更大的灵活性,
任何(Class.Class)
都可以工作,但可能对类型参数
T
的约束不足以适用于某些Mockito语法

Mockito.doReturn(stringResponse)
    .when(mRestAccess)
    .exchange(
         Mockito.anyString(),
         Mockito.any(HttpMethod.class),
         Mockito.any(HttpEntity.class),
         Mockito.eq(byte[].class));

我在Spring的RestClient上有一个类似的用例,即exchange方法,它要求:

restClient.exchange(URI, HttpMethod, HttpEntity, String.class)
我用以下方法解决了这个问题:

ArgumentCaptor<URI> uriCaptor = ArgumentCaptor.forClass(URI.class);
ArgumentCaptor<HttpEntity> entityCaptor = ArgumentCaptor.forClass(HttpEntity.class);
ArgumentCaptor<HttpMethod> methodCaptor = ArgumentCaptor.forClass(HttpMethod.class);
verify(restTemplate, times(1)).exchange(
    uriCaptor.capture(),
    methodCaptor.capture(),
    entityCaptor.capture(),
    Mockito.eq(String.class));
ArgumentCaptor-uriCaptor=ArgumentCaptor.forClass(URI.class);
ArgumentCaptor entityCaptor=ArgumentCaptor.forClass(HttpEntity.class);
ArgumentCaptor methodCaptor=ArgumentCaptor.forClass(HttpMethod.class);
验证(restTemplate,次(1)).exchange(
uriCaptor.capture(),
methodCaptor.capture(),
entityCaptor.capture(),
Mockito.eq(String.class));
然后,除了拦截调用之外,您还有机会检查这些值

您也可以这样做,例如:

doReturn(new ResponseEntity<String>("it works...", 200))
    .when(restTemplate).exchange(
        ArgumentMatchers.eq(uri),
        ArgumentMatchers.eq(HttpMethod.GET),
        ArgumentMatchers.eq(httpEntity),
        Mockito.eq(String.class)
    );
doReturn(新的响应(“它工作…”,200))
.when(rest模板).exchange(
ArgumentMatchers.eq(uri),
ArgumentMatchers.eq(HttpMethod.GET),
ArgumentMatchers.eq(httpEntity),
Mockito.eq(String.class)
);

请解释为什么这里需要Powermockito,而不是问题标签中的Powermockito,并在现场进一步开发答案,而不是将解释放在您自己网站的链接后面。