I need to create a unit test for the following case:
Class under test:
class MyProducer {
private Producer producer = null;
private ProducerCreator producerCreator = null;
public MyProducer() {
producerCreator = ProducerCreator.create(string name);
producer = producerCreator.createProducer();
}
public boolean foo() {
return producer.foo();
}
}
The class ProducerCreator is from an external package with no source code:
public interface ProducerCreator {
static default ProducerCreator create(String name) {
return new ProducerCreatorImpl(...)
}
}
So I am trying to mock the static call with PowerMockito:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ProducerCreator.class)
public class ProducerTest {
@Test
public void fooTest() {
ProducerCreator producerCreatorMock = Mockito.mock(ProducerCreator.class);
PowerMockito.mockStatic(ProducerCreator.class);
PowerMockito.when(ProducerCreator.class, "createProducer", "name").thenReturn(producerCreatorMock);
(Also tried this:
PowerMockito.when(ProducerCreator.create("name")).thenReturn(producerCreatorMock);
But it didn't do any change )
MyProducer myProducer = new MyProducer();
assertTrue(myProducer.foo());
}
Generally I get something like the following:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
...
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
Or any other error or unwanted behaviour instead of a proper mocking. Is the issue due to "static default" method in interface? Didn't find any example for such case in Internet.
UPD: I can't share the real code as it is proprietary.
There is a real static default method from an external package that does compile:
public interface ProducerCreator extends Closeable {
static default ProducerCreator create(String serviceUrl) throws ProducerCreatorException {
return ...
}
UPD 2: The package is a JNI package - generated from CPP code..