Mockito UnfinishedStubbingException with when().thenReturn() - java

I am getting the error message Unfinished Stubbing detected here, when running the following code:
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.*;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
#RunWith(PowerMockRunner.class)
public class PatchWriterTaskTest {
#Before
public void before() throws Exception {
filePath = getFilePath();
task = PowerMockito.spy(new PatchWriterTask());
patchFilesName = new HashMap<Integer, String>();
patchFilesName.put(1, "TCE_RDF_COVERED_DATA_REGION.sql");
scriptPath = new File(filePath + "do_patch_rdf.sql");
PowerMockito.when(task, "getLogger").thenReturn(logger);
PowerMockito.when(task, "getPatchFilesName").thenReturn(patchFilesName);
PowerMockito.when(task, "getDirectoryPath").thenReturn(filePath);
PowerMockito.when(task, "saveDoPatchFile");
}
#Test
public void testUpdateIssuesTable() throws Exception {
PatchWriterTask task = new PatchWriterTask();
Connection conn = mock(Connection.class);
PreparedStatement updateStatement = mock(PreparedStatement.class);
String sql = "update val_issues set PATCH_CREATION_INFO = ? where VAL_ISSUE_ID = ?";
when(conn.prepareStatement(sql)).thenReturn(updateStatement);
The last line throws the error. It doesn't really make sense, as I have done the same code before. Why am I getting this error?
EDIT: I am using powerMockito in order to use the Whitebox.invokeMethod() method, but I also want to use regular Mockito in the rest of the program. Could that be a problem?
Stack Trace:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.PowerMockito.when(PowerMockito.java:426)
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!
at com.navteq.rdf.base.task.PatchWriterTaskTest.testUpdateIssuesTable(PatchWriterTaskTest.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I wanted to add a note that I got this exact same exception, even though my code was written properly. It turned out to be entirely a runtime problem.
My code:
when(service.getChampionById(1, region, null, null)).thenReturn(championList.getChampion(1));
The exception:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at ResourceV1bTest.setUpResources(ResourceV1bTest.java:2168)
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!
It turned out that the following call was throwing an exception, which then triggered the Mockito exception about unfinished stubbing.
championList.getChampion(1)

Seems like the error is pretty clear.
PowerMockito.when(task, "saveDoPatchFile");
...is missing a thenReturn, right?
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();
So why is the exception down in your test method? Neither PowerMock nor Mockito can flag a failure to call thenReturn until the next time you interact with (Power)Mockito or a mock. After all, Mockito and PowerMockito aren't notified that your #Before method ends, and have to accept the "waiting for thenReturn" state. (You're allowed to call mock before thenReturn to allow thenReturn(mock(Foo.class)).)

Related

I am trying to mock a final java class using Mockito 2, class is getting mocked but I still get Unfinished Stubbing Exception

I have included MockMaker file as well- src\test\resources\mockito-extensions\org.mockito.plugins.MockMaker
The related code is as shown where SignatureValidator is final class-
mockValidator = mock(org.opensaml.xmlsec.signature.support.SignatureValidator.class);
mockSignature = mock(SignatureImpl.class);
mockCredential = mock(org.opensaml.security.credential.Credential.class);
#Test(expected = SamlSecurityException.class)
public void testGivenGoodProfileButInvalidSignature() throws SignatureException {
when(mockSamlToken.getSignature()).thenReturn(mockSignature);
when(mockSamlToken.getSAMLIssuerName()).thenReturn("fakeIssuerName");
doThrow(SignatureException.class).when(mockValidator).validate(mockSignature,mockCredential); // getting exception for this line
validator.validate(mockSamlToken);
}
Stack Trace-
java.lang.Exception: Unexpected exception, expected<com.cerner.cto.security.saml.SamlSecurityException> but was<org.mockito.exceptions.misusing.UnfinishedStubbingException>
at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.cerner.cto.security.saml.opensaml.SignatureValidatorTest.testGivenGoodProfileButInvalidSignature(SignatureValidatorTest.java:84)
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, which is not supported
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
at org.opensaml.xmlsec.signature.impl.SignatureImpl.getXMLSignature(SignatureImpl.java:153)
SignatureValidator.validate(...) is a static method, not an instance method; so the statement in question:
doThrow(SignatureException.class).when(mockValidator).validate(mockSignature,mockCredential);
is equivalent to this:
doThrow(SignatureException.class).when(mockValidator);
SignatureValidator.validate(mockSignature,mockCredential);
and I think you can see why that's "unfinished stubbing".
(It's unfortunate that Java even lets you write instance.staticMethod(...) instead of ClassName.staticMethod(...), since the former is so misleading. Some compilers will warn you about this.)
For information about how to mock static methods, see this Stack Overflow question: Mocking static methods with Mockito.

UnfinishedStubbing Exception Mockito

I Was trying to understand basics of testing using PowerMockito to mock static Method as I am new to this.
I am stuck as there is a very unusual situation If I use the below mentioned TestDrink.java I get the UnfinishedStubbingException.
But when I interchange doReurn..When with When..thenReturn Exception disappears.
TestDrink.java
#RunWith(PowerMockRunner.class)
#PrepareForTest({Drink.class,Cola.class})
public class TestDrink {
#Test
public void test()
{
PowerMockito.mockStatic(Cola.class);
/*PowerMockito.when(Cola.drink())
.thenReturn("Drinking");*/
PowerMockito.doReturn("Drinking")
.when(Cola.drink());
System.out.println(Cola.drink());
}
}
This is the class which I am trying to mock.
Cola.java
public class Cola {
public static String drink()
{
return "No drinking";
}
}
Exception
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at TestDrink.test(TestDrink.java:22)
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
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:63)
at com.ayush.rock.Cola.gameOn(Cola.java)
at TestDrink.test(TestDrink.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:106)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
If possible please try to give well-explained answer.
The method you're calling to stub Cola.drink() is:
<T> T org.mockito.stubbing.Stubber.when(T mock)
The method expects a mock, not a real object. Your invocation, however, sends a real string:
PowerMockito.doReturn("Drinking").when(Cola.drink());
In the above line, the actual call is ...when("value returned by actual Cola.drink()")
You can make it work by running:
BDDMockito.given(Cola.drink()).willReturn("Drinking");

NullPointerException when calling mocked method

I try to mock a final method (readChar of class DataInputStream):
MyClassTest
#RunWith(PowerMockRunner.class)
#PrepareForTest(DataInputStream.class)
public class MyClassTest {
#Test
public void testMyMethod() throws IOException {
DataInputStream mockStream = PowerMockito.mock(DataInputStream.class);
Mockito.when(mockStream.readChar()).thenReturn('a');
System.out.println(mockStream.readChar()); // OK (print 'a')
Assert.assertEquals('a', MyClass.myMethod(mockStream));
}
}
MyClass
public class MyClass {
public static char myMethod(DataInputStream dis) throws IOException {
return dis.readChar(); // NPE raises
}
}
It works when calling the mocked method in testMyMethod() but in myMethod() NullPointerException raises, why?
EDIT :
The complete failure trace :
java.lang.NullPointerException
at java.io.DataInputStream.readChar(Unknown Source)
at test.test.MyClass.myMethod(MyClass.java:8)
at test.test.MyClassTest.testMyMethod(MyClassTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:79)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:87)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:77)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:104)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
First this code is a mock antipattern : Don't mock types you don't own! (see this answer on StackOverflow)
Second, DataInputStream is a class of the JDK PowerMock cannot use the same hacky classloader that modifies byte code.
For that there's a solution and two possible tricks :
use the interface
encapsulate the call in a class that you own, then prepare this class instead, documented here at google code, or even better make your own mockable class (without the need of powermock)
use an agent, documented here at google code
The first option is clearly the very best, and the first two options also allows one to avoid this mock antipattern.
DataInputStream is a 'system' class from JVM which is probably already loaded by JVM.
#PrepareForTest would have to remove final modifier from the methods (to be able to mock), but it can't do so for already-loaded classes (HotSpot JVM doesn't support class signature changes for already-loaded classes), and this is probably why you get this exception.
Luckily there's also DataInput interface implemented by DataInputStream - maybe you can try mocking not DataInputStream but DataInput, for this you don't even need PowerMock, just Mockito.

Mockito + PowerMock LinkageError while mocking system class

I've got such a code snippet:
#RunWith(PowerMockRunner.class)
#PrepareForTest({Thread.class})
public class AllMeasuresDataTest {
#Before
public void setUp() throws Exception {
}
#Test
public void testGetMeasures() {
AllMeasuresData measure = new AllMeasuresData();
assertEquals(measure.getMeasures(), null);
HashMap<String, Measure> map = new HashMap<String, Measure>();
measure.setMeasures(map);
assertEquals(measure.getMeasures(), map);
measure.setMeasures(null);
assertEquals(measure.getMeasures(), null);
}
#Test
public void testAllMeasuresData() throws IOException {
ClassLoader loader = PowerMockito.mock(ClassLoader.class);
Thread threadMock = PowerMockito.mock(Thread.class);
Vector<URL> vec = new Vector<URL>();
Mockito.when(loader.getResources("measure")).thenReturn(vec.elements());
Mockito.when(threadMock.getContextClassLoader()).thenReturn(loader);
PowerMockito.mockStatic(Thread.class);
Mockito.when(Thread.currentThread()).thenReturn(threadMock);
...
}
}
While running this tests I got:
java.lang.LinkageError: loader constraint violation: loader (instance of org/powermock/core/classloader/MockClassLoader) previously initiated loading for a different type with name "javax/management/MBeanServer"
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
at org.powermock.core.classloader.MockClassLoader.loadUnmockedClass(MockClassLoader.java:201)
at org.powermock.core.classloader.MockClassLoader.loadModifiedClass(MockClassLoader.java:149)
at org.powermock.core.classloader.DeferSupportingClassLoader.loadClass(DeferSupportingClassLoader.java:67)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at org.codecover.instrumentation.java.measurement.ProtocolImpl.initializeMBean(ProtocolImpl.java:247)
at org.codecover.instrumentation.java.measurement.ProtocolImpl.<init>(ProtocolImpl.java:237)
at org.codecover.instrumentation.java.measurement.ProtocolImpl.getInstance(ProtocolImpl.java:185)
at measure.CodeCoverCoverageCounter$6ya5ud0ow79ijrr1dvjrp4nxx60qhxeua02ta2fzpmb1d.<clinit>(MeasureCalculatorsHolder.java:146)
at measure.MeasureCalculatorsHolder.<clinit>(MeasureCalculatorsHolder.java:17)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:188)
at javassist.runtime.Desc.getClassObject(Desc.java:43)
at javassist.runtime.Desc.getClassType(Desc.java:152)
at javassist.runtime.Desc.getType(Desc.java:122)
at javassist.runtime.Desc.getType(Desc.java:78)
at algorithm.AllMeasuresDataTest.testGetMeasures(AllMeasuresDataTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:312)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:296)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl$PowerMockJUnit49MethodRunner.executeTestInSuper(PowerMockJUnit49RunnerDelegateImpl.java:116)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl$PowerMockJUnit49MethodRunner.executeTest(PowerMockJUnit49RunnerDelegateImpl.java:77)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:284)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:209)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:148)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:122)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.codecover.juniteclipse.runner.EclipseTestRunner.main(EclipseTestRunner.java:40)
Do you know how can I prevent this? I maybe there is another way to mock such a piece of code:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
...
Enumeration<URL> resources = classLoader.getResources(path);
Try adding this annotation to your Test class:
#PowerMockIgnore("javax.management.*")
Worked for me.
Similar to the accepted response here, I ended up having to exclude all of the SSL related classes:
#PowerMockIgnore({"javax.management.*", "org.apache.http.conn.ssl.*", "com.amazonaws.http.conn.ssl.*", "javax.net.ssl.*"})
Adding that to the top of my class resolved the error.
Classloader conflict, use this: #PowerMockIgnore("javax.management.*")
Let mock classloader do not load javax.*.
It works.
This may be a bit of an old topic, but I have also ran into this problem. Turns out that some of the java versions cannot handle powermockito when powermock finds out there are 2 classes with the same name in the same package (over different dependencies).
With any version higher than Java 7_25 it gives this error.
In PowerMock 1.7.0 a user-defined global configuration can be added to your project's classpath. PowerMockConfig
org/powermock/extensions/configuration.properties
Simply add a line in the properties file like:
powermock.global-ignore=javax.management.*
This will resolve the error for all the test classes in your project.
In order to mock system classes, prepare the class that is the target of the test, not Thread.class. There's no way PowerMock will be able to instrument Thread.class because it is required during JVM startup - well before PowerMock can instrument.
The way instrumentation works, once a class is loaded, it can no longer be intstrumented.
See the PowerMock wiki.
Depending on your individual setup, it may be necessary to add more methods to #PowerMockIgnore. I stumbled over this with slf4j, for using PowerMock and slf4j together, you'll need
#PowerMockIgnore({ "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*", "org.w3c.dom.*" })

Mockito exception in doThrow that looks correct

I'm trying to mock a method to see if I handle an exception correctly. This is as far as I get.
interface:
interface SampleManager {
void deleteVariome(String specimenId, String analysisId) throws Exception;
// ...
}
unit test:
// ...
SampleManger sampleManager = mock(SampleManager.class);
// below is line 753
doThrow(Exception.class).when(sampleManager).deleteVariome(sample1.getId(), analysisId);
result:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at ...server.ArchiveManagerImplUTest.deleteVariomeFails(ArchiveManagerImplUTest.java:753)
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(); <-- this looks a log like what I did!
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer! <-- I have a lot of other mocks of this interface in this test that work.
From an identical issue that I just ran into, I suspect that sample is a mock, and you stubbed sample.getId() elsewhere? That caused this problem in my case, anyhow.
For some reason, Mockito gets upset if one of the arguments you pass to the stub used with doThrow in this way is the result of a method you also mocked. Perhaps it's a re-entrancy check of sorts to avoid infinite loops, I don't know.
Regardless, try replacing sample.getId() with a constant value and that should solve the issue. You could consider using a constant declared in your test for both the mock and any further uses of it. You could then also check that sample.getId() was used by the method you're testing by adding another call to verify.
This error is usually reported AFTER the place where it actually occurred. If you fail to stub something properly, Mockito usually can't tell until the NEXT time you call one of the Mockito methods. This might be in the same test method, a later test method in the same class, or even an entirely different test class.
The line that you've quoted looks fine to me. Take a look at the lines above it, where you call a Mockito stubbing or verification method. It's very likely that you have a when that has no associated thenReturn, then or thenThrow. Or you might have a verify that's missing the actual method call. There are a few other possibilities too.
If you can't find an error in the lines ABOVE the one that you've quoted, then post some more of your code, and I'll take a closer look.
As described in the answer by Gijs, this is probably due to a bug in Mockito. Here is a complete test which reproduces it:
interface Sample { String getId(); }
interface SampleManager {
void deleteVariome(String specimenId, String analysisId);
}
#Test
public void probableMockitoBug() {
Sample sample1 = mock(Sample.class);
when(sample1.getId()).thenReturn("a");
SampleManager manager = mock(SampleManager.class);
doThrow(Exception.class).when(manager).deleteVariome(sample1.getId(), "b");
manager.deleteVariome("a", "b");
}
The test produces the following output:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.mockitousage.JavadocExamplesTest.probableMockitoBug(JavadocExamplesTest.java:404)
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!
at org.mockito.exceptions.Reporter.unfinishedStubbing(Reporter.java:55)
at org.mockito.internal.progress.MockingProgressImpl.validateState(MockingProgressImpl.java:74)
at org.mockito.internal.progress.ThreadSafeMockingProgress.validateState(ThreadSafeMockingProgress.java:49)
at org.mockito.internal.MockHandler.handle(MockHandler.java:71)
at org.mockito.internal.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:36)
at org.mockito.internal.creation.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:48)
at org.mockitousage.JavadocExamplesTest$Sample$$EnhancerByMockitoWithCGLIB$$d5ac41.getId()
at org.mockitousage.JavadocExamplesTest.probableMockitoBug(JavadocExamplesTest.java:404)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
you have to supply an instance of the Exception.class not the Exception class itself.
doThrow(new Exception()).when(sampleManager).deleteVariome(sample1.getId(), analysisId);
EDIT
Well #DavidWallace corrected me, so be warned (or rather enlightened) that since 1.9 you can just provide the exception class to throw and it will construct one for you.

Categories