模拟方法包含函数和对象作为参数?

问题描述 投票:0回答:1

编写 Junit 单元测试用例,我尝试使用 Mockito 模拟方法调用服务。

public CompletableFuture<String> getInfo(String something) 
{

CompletableFuture<String> future = new CompletableFuture<>();
JAXBElement<Class1> request = SoapRequests
        .buildRequest(str1, str2);
        
Consumer<Exception> exception = ex->{
future.complete("exception");  
}

Consumer<FaultType> fault = fault->{
future.complete("exception",FaultType.class);  
}

String target="target";

JAXBElement<?> element = soapConnector.callservice(
        target, request,
        fault, ex, false);

}

我尝试过以下方法。但是,它总是返回空元素

JAXBElement<?> response = jaxbUnmarshaller.unmarshal("xmlString",
          SomeClass12.class);

JAXBElement<SomeClass> request = SoapRequests
          .buildRequest("", "", "");
JAXBElement<SomeClass> requestSpy = spy(request);         

Consumer<FaultType> faultType = mock(Consumer.class);
Consumer<Exception> exception = mock(Consumer.class);

 lenient().when(soapConnector.callservice(
          "target", requestSpy,
          faultType, exception, false)).thenAnswer(i->response);
java mockito junit5 springmockito
1个回答
0
投票

如果你想模拟一个带参数的方法,mockito 使用 equal 方法来比较参数。如果它们等于调用模拟的参数,模拟将返回该值。如果没有找到匹配项,您的模拟将返回 null。在您的情况下,相等性检查永远不会返回 true,因为某些参数是您的测试用例的本地参数,因此模拟返回 null。

具体来说,requestSpy 不等于实际代码中的 request,消费者模拟也不等于,因为它们是局部变量,也是模拟。

我不太确定你想做什么,但在模拟函数时没有必要传递模拟。正确模拟你的功能的一种可能方法是:

Mockito<JAXBElement<?>>.when(soapConnector.callservice(
          eq("target"), any(),
          any(), any(), eq(false))).thenReturn(response);

通过这种方式,我们确保提供了参数 target 和 false,并且并不真正关心其他参数。如果您想检查参数,请使用 ArgumentCaptor。

另请注意我如何显式定义 when() 函数的通用参数以确保输入正确。

© www.soinside.com 2019 - 2024. All rights reserved.