- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
首先,我尝试为远程服务编写单元测试来获取天气并使用restTemplate,然后实现 ClientHttpRequestInterceptor
为了获取远程请求和远程响应以进行日志记录,现在我尝试模拟restTemplate来编写单元测试并得到以下错误
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
and here you here code i wrote for unit-test
@RunWith(MockitoJUnitRunner.class)
public class WeatherRemoteServiceTest {
@Mock CustomResttemplate restTemplate;
@Mock WeatherRemoteUtilies weatherUtilies;
@InjectMocks WeatherRemoteService weatherRemote;
@Test
public void testRetrieveWeather() {
ResponseEntity<String> MockResponse= new ResponseEntity<String>(HttpStatus.OK);
Mockito.when(weatherUtilies.buildRequestParams(Mockito.anyString()))
.thenReturn(Mockito.any(MultiValueMap.class));
ResponseEntity<String> responseEntity = new ResponseEntity<String>("sampleBodyString", HttpStatus.OK);
Mockito.when(restTemplate.buildRestTemplate().exchange(
Matchers.anyString(),
Matchers.any(HttpMethod.class),
Matchers.<HttpEntity<?>> any(),
Matchers.<Class<String>> any()
)
).thenReturn(responseEntity);
assertEquals(weatherRemote.retrieveWeather("ciaro").getStatusCode(), HttpStatus.OK);
}
}
这是业务逻辑本身的代码
@Service
public class WeatherRemoteService {
private final Logger logger= LoggerFactory.getLogger(this.getClass());
@Value("${openweather.url}")
private String url;
@Autowired
private WeatherRemoteUtilies weatherUtilies;
@Autowired
private CustomResttemplate customRestTemplate;
public ResponseEntity<?> retrieveWeather(String city) {
logger.info(Constants.CLASS_NAME+this.getClass().getName()+Constants.METHOD_NAME+new Object() {}.getClass().getEnclosingMethod().getName());
logger.debug(Constants.METHOD_ARGUMENTS+city);
RestTemplate restRequest= customRestTemplate.buildRestTemplate();
HttpHeaders headers= new HttpHeaders();
headers.set("Accept",MediaType.APPLICATION_JSON_UTF8_VALUE);
UriComponentsBuilder uri= UriComponentsBuilder.fromUriString(url).
path("/data/2.5/weather")
.queryParams(weatherUtilies.buildRequestParams(city));
HttpEntity<String>entity= new HttpEntity<>(headers);
ResponseEntity<String>WeatherResponse=restRequest.exchange(uri.toUriString(), HttpMethod.GET, entity, String.class);
logger.info(Constants.END_METHOD);
return WeatherResponse;
}
}
代码RestTemplateInterceptor
public class RestTemplateInterceptor implements ClientHttpRequestInterceptor {
private final Logger logger =LoggerFactory.getLogger(this.getClass());
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
logRequest(request, body);
ClientHttpResponse httpResponse= execution.execute(request, body);
logResponse(httpResponse);
return httpResponse;
}
private void logRequest(HttpRequest request, byte[] body) throws IOException {
logger.info(Constants.START_REMOTE_REQUEST);
logger.info("URI :{}", request.getURI().toString());
logger.info("Method :{}", request.getMethod().toString());
logger.info("Headers :{}", request.getHeaders().toString());
logger.info("Request body :{}", new String(body,"UTF-8").toString());
logger.info(Constants.END_REMOTE_REQUEST);
}
private void logResponse(ClientHttpResponse response) throws IOException {
logger.info(Constants.START_REMOTE_RESPONSE);
logger.info("Status code :{}", response.getStatusCode().toString());
logger.info("Status text :{}", response.getStatusText().toString());
logger.info("Headers :{}", response.getHeaders().toString());
logger.info("Response body :{}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));
logger.info(Constants.END_REMOTE_RESPONSE);
}
}
然后使用以下代码在 RestTemplate 工厂上 setInterceptor
public class CustomResttemplate {
public RestTemplate buildRestTemplate() {
SimpleClientHttpRequestFactory simpleFactory= new SimpleClientHttpRequestFactory();
simpleFactory.setOutputStreaming(false);
ClientHttpRequestFactory factory = new BufferingClientHttpRequestFactory(simpleFactory);
RestTemplate restTemplate= new RestTemplate(factory);
restTemplate.setInterceptors(Collections.singletonList(new RestTemplateInterceptor()));
return restTemplate;
}
}
最佳答案
你的问题在于你写的地方
.thenReturn(Mockito.any(MultiValueMap.class))
您实际上必须告诉 Mockito 要返回什么。您不能在这里使用匹配器。匹配器用于验证并设置要 stub 的条件。您不能使用它们来告诉 Mockito 从 stub 调用中返回什么。
创建一个特定的MultiValueMap
以传递给thenReturn
。
关于java - Mockito org.mockito.exceptions.misusing.InvalidUseOfMatchersException : Invalid use of argument matchers! 预期 0 个匹配器,记录 1 个:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078029/
我一直面临一个奇怪的问题。基本上,当我正常运行 Mockito 测试时,即“作为 Junit 测试运行”时,它给了我以下错误。有人可以帮助我请问我的错误是什么? 收到的错误: java.lan
我正在使用 Mockito 以及 mockito-inline用于模拟静态方法。我正在尝试申请 doNothing或类似的行为,到静态 void 方法。以下解决方法有效,但我认为应该有一种更方便的方法
我正在尝试验证我正在测试的类是否调用了正确的依赖类的方法。所以我试图匹配方法参数,但我并不真正关心这个测试中的实际值,因为我不想让我的测试变得脆弱。 但是,我在设置它时遇到了麻烦,因为 Mockito
我正在使用 Mockito 编写单元测试,并且在模拟注入(inject)的类时遇到问题。问题是两个注入(inject)的类是相同的类型,仅通过它们的 @Qualifier 注释进行区分。如果我尝试简单
在我的断言中的以下简单练习中,我期望 1,但得到 0。为什么我会看到这种行为? public class MockitoTest { POJO mockedPojo; @Before
我正在创建一个通用模拟客户端来测试 HTTP 交互。为此,我希望能够以相同的方法进行多次响应。使用普通模拟,这不是问题: when(mock.execute(any(), any(), any()))
我需要全局模拟类方法。 我的意思是,我不能创建模拟对象和 stub 方法。我的 api 不将此对象作为参数,所以我不能在函数调用中传递它,但是这个类的对象是在这些函数中创建并在那里使用的。这就是为什么
我正在尝试使用 Mockito 2.18.3 框架模拟我们公司内部库中提供的 final 类,不幸的是我们无权更改库中的代码。但每当我运行时,我都会收到以下错误: java.lang.NoClassD
研究了mockito测试框架,学习了powermock,突然发现一个叫powermockito的框架,看不懂了。 谁能告诉我这三个测试工具的区别? 最佳答案 Mockito 是市场标准模拟框架,味道非
我想跳过检查验证调用中的参数之一。因此对于: def allowMockitoVerify=Mockito.verify(msg,atLeastOnce()).handle(1st param,,3r
为了模拟在被测方法内部构造的本地对象上的局部变量/方法调用,我们目前使用的是 PowerMockito 库。 我们正在尝试评估是否可以使用 mockito-inline(版本 3.7.7)来做同样的事
我在想, 如果在 @Before 方法中我正在初始化模拟对象,我不应该在 @After 中取消对它的引用吗?或者那会是多余的吗?为什么? 最佳答案 不需要,JUnit 会为每个测试方法创建一个新的测试
我想使用 Mockito 验证字符串参数是否满足两个条件: verify(mockClass).doSomething(Matchers.startsWith("prefix")); verify(m
如果我像这样创建一个模拟 when(servicesTestEnv.mockUserProfileAndPortfolioTransactionRepository.get(servicesTestE
使用 Mockito 我遇到了以下问题: Mockito.when(restOperationMock.exchange( Mockito.anyString(), M
我想知道描述中的事情是否可行以及如何去做。 我知道你可以调用原始方法然后像这样做答案: when(presenter, "myMethod").doAnswer() 但我想对它们进行不同的排序,首先执
我试图弄清楚org.mockito.AdditionalMatchers是如何工作的,但我失败了。为什么这个测试失败了? import static org.hamcrest.CoreMatchers
有人知道使用 Mockito 为 ATG 编写单元测试用例吗?我在凝视时遇到了以下讨论 - Automated unit tests for ATG development和 Using PowerM
我想知道描述中的事情是否可行以及如何去做。 我知道你可以调用原始方法然后像这样做答案: when(presenter, "myMethod").doAnswer() 但我想对它们进行不同的排序,首先执
我有以下接口(interface)CatalogVersionService,它公开了一些服务。我还有一个单元测试,它通过使用 Mockito 来模拟这个接口(interface),如下所示: Cat
我是一名优秀的程序员,十分优秀!