我正在使用的静态方法之一,它做了两件事。它返回一些数据,但它也修改传递给它的参数对象。然后在代码中使用此更新的参数对象。
One of static method I am using, it does two things. It returns some data, but it also modifies the argument object that is passed to it. This updated argument object is then used later in code.
我使用PowerMock来模拟返回行为。
I am using PowerMock to mock the return behavior.
为了定义第二部分 - 更新输入参数,我正在定义doAnswer方法,但它不起作用。我正在尝试测试的方法如下所示。
For defining the second part - updating the input argument, I am defining doAnswer method but it's not working. The method that I'm trying to test looks like this.
public void login() throws ConnectionException, AsyncApiException { ConnectorConfig partnerConfig = new ConnectorConfig(); //This call sets the value in one member variable 'serviceEndPoint in ParterConfig which is accessed later in this method only. partnerConnection = Connector.newConnection(partnerConfig); //partnerConfig.getServiceEndpoint is called. PowerMockito.mockStatic(Connector.class); when(Connector.newConnection(Mockito.any(ConnectorConfig.class))).thenReturn(partnerConnection); PowerMockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { ConnectorConfig config = (ConnectorConfig) invocation.getArguments()[0]; config.setServiceEndpoint("service end point"); return null; } }).when(Connector.newConnection(Mockito.any(ConnectorConfig.class))); }但是在上面抛出错误,说'在这里检测到未完成的存根'。 连接器是第三方类,因此我无法控制其行为。
but above throws error saying 'Unfinished stubbing detected here'. Connector is a third party class so I don't have control over its behavior.
任何建议,可能出现什么问题?
Any suggestions, what could be going wrong?
推荐答案PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.newConnection(Mockito.any(ConnectorConfig.class)));
当出现问题时你的。在正常的Mockito中,使用任何 doAnswer / doReturn / etc调用,你必须拨打你正在打断的电话<在时调用的外部,如下所示:
Your when is the problem. In normal Mockito, using any doAnswer/doReturn/etc call, you have to place the call you're stubbing outside of the call to when, like so:
Mockito.doAnswer(new Answer<Void>() { /* ... */ }).when(yourMock).callVoidMethod(); // ^^^^^^PowerMockito还需要调用静态方法在下一个声明中,如下所示:
PowerMockito further requires that calls to static methods happen in the next statement, like so:
PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.class); Connector.newConnection(/*...*/); // ^^^^^^请注意我链接的文档实际上是不一致的 - 看起来文档在时提到零参数,而在可用的签名中需要类文字。如果你有一个时刻,那么标记为错误可能是一件好事。
Note that the documentation I linked is actually inconsistent--looks like the docs allude to a zero-arg when, whereas the class literal is required in the signatures available. That might be a good thing to flag as a bug, if you have a moment.
强制性PSA:通常一个好主意避免嘲笑你不拥有的类型,虽然陪审团仍然在那个上。
Obligatory PSA: It's generally a good idea to avoid mocking types you don't own, though the jury's still out on that one.
更多推荐
doAnswer用于静态方法
发布评论