DoAnswer for static methods - PowerMock

One of the static methods that I use does two things. It returns some data, but also modifies the argument object passed to it. This updated argument object is then used later in the code.

I use PowerMock to make fun of return behavior.

To determine the second part - updating the input argument, I define the doAnswer method, but it does not work. The method I'm trying to test is as follows.

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, an error appears saying that "An incomplete interrupt was detected." Connector is a third-party class, so I do not control its behavior.

Any suggestions what could be wrong?

+6
source share
1 answer
 PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.newConnection(Mockito.any(ConnectorConfig.class))); 

Your problem is when . In a regular Mockito, using any call to doAnswer / doReturn / etc, you should put the call that you are doReturn outside the call to on when , for example:

 Mockito.doAnswer(new Answer<Void>() { /* ... */ }).when(yourMock).callVoidMethod(); // ^^^^^^ 

PowerMockito additionally requires that static method calls be made in the following statement , for example:

 PowerMockito.doAnswer(new Answer<Void>() { /* ... */ }).when(Connector.class); Connector.newConnection(/*...*/); // ^^^^^^ 

Please note that the documentation I am associated with is actually incompatible - it seems that the documents are referencing zero-arg when , while the class literals are required in the available signatures. Perhaps it would be nice to mark it as an error if you have a moment.

Mandatory PSA: It’s usually a good idea to avoid ridicule of types that you don’t own , although the jury is still there .

+12
source

Source: https://habr.com/ru/post/951079/


All Articles