gpt4 book ai didi

java - mockito 拒绝将 TypeSafeMatcher 与通用方法 API 配对

转载 作者:行者123 更新时间:2023-11-29 06:51:53 25 4
gpt4 key购买 nike

我想测试调用某些 API 的代码:

public <T extends MessageLite> ApiFuture<String> publish(final T message) throws Exception {
}


public <T extends MessageLite> ApiFuture<String> publish(final T message, final ApiFutureCallback<T> futureCallback) throws Exception {
}


public <T> String publishSynchronous(final String message, final ApiFutureCallback<T> futureCallback) throws Exception {
}

在我的测试中,我使用 mockito mock,然后我想验证它是使用具有字段 isSuccess = false

的原型(prototype)对象(扩展 MessageLite)调用的

我厌倦了这段代码:

    verify(customPublisher, times(0)).publish(isFailureResult(), anyObject());

和这个匹配器:

public class FailResultMatcher extends TypeSafeMatcher<MessageLite> {

@Override
protected boolean matchesSafely(final MessageLite sentResult) {
return !((SdkResult)sentResult).getIsSuccess();
}


public static FailResultMatcher isFailureResult() {
return new FailResultMatcher();
}

@Override
public void describeTo(final Description description) {

}
}

但我在测试编译时遇到错误:

Error:(131, 42) java: no suitable method found for publish(com.w.sdkService.matchers.FailResultMatcher,java.lang.Object)
method linqmap.cloud.google.pubsub.CustomPublisher.<T>publish(java.lang.String,com.google.api.core.ApiFutureCallback<T>) is not applicable
(cannot infer type-variable(s) T
(argument mismatch; com.w.sdkService.matchers.FailResultMatcher cannot be converted to java.lang.String))
method linqmap.cloud.google.pubsub.CustomPublisher.<T>publish(T) is not applicable
(cannot infer type-variable(s) T
(actual and formal argument lists differ in length))
method linqmap.cloud.google.pubsub.CustomPublisher.<T>publish(T,com.google.api.core.ApiFutureCallback<T>) is not applicable
(inferred type does not conform to upper bound(s)
inferred: com.w.sdkService.matchers.FailResultMatcher
upper bound(s): com.google.protobuf.MessageLite)

我该如何解决这个问题?

最佳答案

根据文档(Mockito 1Mockito 2),您必须使用 argThat(matcher),这是一个允许您使用自定义参数匹配器的 Mockito 匹配器:

 //stubbing
when(mock.giveMe(argThat(new MyHamcrestMatcher())));

//verification
verify(mock).giveMe(argThat(new MyHamcrestMatcher()));

你没有说你使用的是 Mockito 1 还是 2,但想法是相似的,只是静态导入不同:

  • 1: import static org.mockito.Matchers.argThat;(或者为简单起见 org.mockito.Mockito 扩展了 Matchers)
  • 2: import static org.mockito.hamcrest.MockitoHamcrest.argThat;

额外提示,为了便于阅读,您可以将 times(0) 替换为 never() ,所以在你的情况下它将是:

verify(customPublisher, never()).publish(argThat(isFailureResult()), anyObject());

关于java - mockito 拒绝将 TypeSafeMatcher 与通用方法 API 配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45331645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com