首页 > 解决方案 > 在调用时需要但未调用

问题描述

我正在尝试验证是否使用 Mockito.verify 调用了 OAuth2RestTemplate patchForObject 方法,但它根本不起作用。我还有其他无法正常工作的模拟方法,例如 getForObject 没有被正确存根,而是返回默认的 null 。这是我的代码:

@RunWith(MockitoJUnitRunner.class)
public class ClientPaasTest {
    @Mock
    private OAuth2RestTemplate clientCredentialsRestTemplateMock;

    @InjectMocks
    private ClientPaas clientPaas;

    @Before
    public void setup() {
        Mockito.reset(clientCredentialsRestTemplateMock);
    }
    @Test
    public void testPatchCarteJetonInterac() {
        clientPaas.patchCarteJetonInterac(null, "carte1");   
        Mockito.verify(clientCredentialsRestTemplateMock).patchForObject(null, null, Object.class);
    }
}

我收到以下错误:

Wanted but not invoked:
clientCredentialsRestTemplateMock.patchForObject(
    null,
    null,
    class java.lang.Object
);
-> at com.pmtcartes.util.ClientPaasTest.testPatchCarteJetonInterac
(ClientPaasTest.java:91)

However, there were other interactions with this mock:
clientCredentialsRestTemplateMock.patchForObject(
    null,
    null,
    class java.lang.Object
);
-> at
com.pmtcartes.util.ClientPaas.patchCarteJetonInterac(ClientPaas.java:70)

哪个对我来说看起来完全一样......有人有解决方案吗?我已经在许多其他项目中多次这样做了。我不确定发生了什么。

标签: javatestingjunitmockitoverify

解决方案


我发现了原因。模拟使用不同的签名存根 OAuth2RestTemplate.getForObject 或 patchForObject。嘲笑:

public <T> T patchForObject(String url, Object request, Class<T> responseType,
        Object... uriVariables) throws RestClientException {

代替 :

public <T> T patchForObject(URI url, Object request, Class<T> responseType) 
        throws RestClientException {

推荐阅读