InetAddress static method doesn't mock with PowerMockito - junit

I am running into weird problem while trying to mock static methods in InetAddress. I am successfully able to mock static methods for many of other classes and all works fine, but InetAddress showing different behavior. I am using JUnit 4.x, Mockito 1.9.5 & PowerMock 1.5.6.
Given below test using Mockito and PowerMock, and InetAddress mocking works fine -
#RunWith(PowerMockRunner.class)
#PrepareForTest({InetAddress.class})
public class UtilityTest {
#Mock
InetAddress inetAddress;
#Test
public void testGetCurrentHost() throws UnknownHostException {
mockStatic(InetAddress.class);
when(InetAddress.getLocalHost()).thenReturn(inetAddress);
when(inetAddress.getHostAddress()).thenReturn("1.1.1.1");
assertEquals("1.1.1.1", getCurrentHost());
}
private static String getCurrentHost() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
}
When I put the given below method in some utility, InetAddress.getLocalHost() doesn't mock anymore and test fails.
Move it to Utility :
private static String getCurrentHost() throws UnknownHostException {
return InetAddress.getLocalHost().getHostAddress();
}
Now my test looks like (and fails) :
#RunWith(PowerMockRunner.class)
#PrepareForTest({InetAddress.class})
public class UtilityTest {
#Mock
InetAddress inetAddress;
#Test
public void testGetCurrentHost() throws UnknownHostException {
mockStatic(InetAddress.class);
when(InetAddress.getLocalHost()).thenReturn(inetAddress);
when(inetAddress.getHostAddress()).thenReturn("1.1.1.1");
assertEquals("1.1.1.1", Utility.getCurrentHost());
}
}
Given below is my stacktrace -
org.junit.ComparisonFailure:
Expected :1.1.1.1
Actual :192.111.111.121
<Click to see difference>
at org.junit.Assert.assertEquals(Assert.java:115)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.somecompany.helper.INetTest.testGetCurrentHost(INetTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
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:88)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
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:86)
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:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
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.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Process finished with exit code -1

I know that this post is kind old, but I found a solution.
Instead doing #PrepareForTest({ InetAddress.class }), you must do #PrepareForTest({ YouClassThatWrap.class }).
In here (https://code.google.com/p/powermock/wiki/MockSystem) it shows how to mock a SystemClass.
The code #PrepareForTest({ InetAddress.class }) will not work because Powermock cannot change a System class code, so you need to mock the "wrapper" class.

I found a solution.
change #PrepareForTest({InetAddress.class}) to #PrepareForTest({Utility .class, InetAddress.class})

Related

Mockito cannot mock JdbcTemplate

I'm currently working on setting up JUnit tests using Mockito. As of right now, I'm unable to get a very basic test to run:
#ExtendWith(MockitoExtension.class)
public class TestDAO {
private final Logger logger = LoggerFactory.getLogger(TestDAO.class.getName());
#Mock
public JdbcTemplate jdbcTemplate = new JdbcTemplate();
#InjectMocks
private TestDAOImpl dao;
#Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
#BeforeEach
public void init() {
System.out.println("Hello init");
}
#Test
public void getAllEntries() {
System.out.println("hello world");
}
}
For the moment, all I want is to see if it can print out hello world. Every time I run the test, though, I receive an error that:
Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class
Which seems to point to the JdbcTemplate as the culprit. I'm trying to mock that database connection so I can mock CRUD operations later.
This is my first time using Mockito, so any help would be appreciated. The full stack trace is below:
org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class org.springframework.jdbc.core.JdbcTemplate.
Mockito can only mock non-private & non-final classes.
If you're not sure why you're getting this error, please report to the mailing list.
Java : 1.8
JVM vendor name : Oracle Corporation
JVM vendor version : 25.5-b02
JVM name : Java HotSpot(TM) Client VM
JVM version : 1.8.0_05-b13
JVM info : mixed mode
OS name : Windows 7
OS version : 6.1
Underlying exception : java.lang.IllegalArgumentException: object is not an instance of declaring class
at org.mockito.junit.jupiter.MockitoExtension.beforeEach(MockitoExtension.java:165)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$0(TestMethodTestDescriptor.java:129)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$192/20816428.execute(Unknown Source)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:155)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:128)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:107)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$145/18524506.accept(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$145/18524506.accept(Unknown Source)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor$$Lambda$142/16902902.execute(Unknown Source)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:74)
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)
Suppressed: java.lang.NullPointerException
at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:211)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$11(TestMethodTestDescriptor.java:217)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$196/31005110.execute(Unknown Source)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:229)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor$$Lambda$195/6646756.accept(Unknown Source)
at java.util.ArrayList.forEach(ArrayList.java:1234)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:227)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:216)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:119)
... 49 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
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:483)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3083)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator$Chained.resolve(TypeDescription.java:2868)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$ForTypeArgument.resolve(TypeDescription.java:3056)
at net.bytebuddy.description.type.TypeDescription$Generic$AnnotationReader$Delegator.asList(TypeDescription.java:2822)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$ForLoadedType.getDeclaredAnnotations(TypeDescription.java:5130)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$Symbolic.getDeclaredAnnotations(TypeDescription.java:4941)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable$WithAnnotationOverlay.getDeclaredAnnotations(TypeDescription.java:5204)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.apply(AnnotationAppender.java:639)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onTypeVariable(AnnotationAppender.java:611)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onTypeVariable(AnnotationAppender.java:333)
at net.bytebuddy.description.type.TypeDescription$Generic$OfTypeVariable.accept(TypeDescription.java:4852)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onParameterizedType(AnnotationAppender.java:601)
at net.bytebuddy.implementation.attribute.AnnotationAppender$ForTypeAnnotations.onParameterizedType(AnnotationAppender.java:333)
at net.bytebuddy.description.type.TypeDescription$Generic$OfParameterizedType.accept(TypeDescription.java:4372)
at net.bytebuddy.implementation.attribute.MethodAttributeAppender$ForInstrumentedMethod.apply(MethodAttributeAppender.java:183)
at net.bytebuddy.implementation.attribute.MethodAttributeAppender$Compound.apply(MethodAttributeAppender.java:425)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyAttributes(TypeWriter.java:617)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod$WithBody.applyBody(TypeWriter.java:609)
at net.bytebuddy.dynamic.scaffold.TypeWriter$MethodPool$Record$ForDefinedMethod.apply(TypeWriter.java:528)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default$ForCreation.create(TypeWriter.java:4167)
at net.bytebuddy.dynamic.scaffold.TypeWriter$Default.make(TypeWriter.java:1653)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:183)
at net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder.make(SubclassDynamicTypeBuilder.java:163)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase.make(DynamicType.java:2669)
at net.bytebuddy.dynamic.DynamicType$Builder$AbstractBase$Delegator.make(DynamicType.java:2771)
at org.mockito.internal.creation.bytebuddy.SubclassBytecodeGenerator.mockClass(SubclassBytecodeGenerator.java:128)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:37)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator$1.call(TypeCachingBytecodeGenerator.java:34)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:137)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:344)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:159)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:353)
at org.mockito.internal.creation.bytebuddy.TypeCachingBytecodeGenerator.mockClass(TypeCachingBytecodeGenerator.java:32)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMockType(SubclassByteBuddyMockMaker.java:71)
at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:42)
at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)
at org.mockito.Mockito.mock(Mockito.java:1895)
at org.mockito.internal.configuration.MockAnnotationProcessor.processAnnotationForMock(MockAnnotationProcessor.java:41)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:19)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.IndependentAnnotationEngine.createMockFor(IndependentAnnotationEngine.java:38)
at org.mockito.internal.configuration.IndependentAnnotationEngine.process(IndependentAnnotationEngine.java:62)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:57)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:41)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
at org.mockito.internal.framework.DefaultMockitoSession.<init>(DefaultMockitoSession.java:36)
at org.mockito.internal.session.DefaultMockitoSessionBuilder.startMocking(DefaultMockitoSessionBuilder.java:78)
... 56 more
Please recheck your imports and don't mix JUnit 4 and JUnit 5, it may be the source of your problem.
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.jdbc.core.JdbcTemplate;
#ExtendWith ( MockitoExtension.class )
public class SampleTest {
#Mock
private JdbcTemplate jdbcTemplate = new JdbcTemplate();
#InjectMocks
private TestObject testObject;
#BeforeEach
public void init() {
System.out.println( "Hello init" );
}
#Test
public void getAllEntries() {
System.out.println( "hello world" );
}
}
It is working perfectly with my example. Be careful with #Test annotation - it has to be JUnit 5 annotation, moreover #Rule annotation doesn't exist in JUnit 5.
If it won't help, please show us your dependencies with versions.

MessageBodyWriter not found for media type=text/xml or type=text/plain when throwing an exception

I am getting an Exception
"MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=text/xml, type=class ..."
when an exception is thrown from within an application on Glassfish 4.1.
Before activation of Jackson instead of Moxy/Jaxb everything was fine.
Verify if your MessageBodyWriterAdater is producing the same media type as your services/methods.
They have to be consistent or you just have to write additional MessageBodyWriterAdapters for unsupported types.
e.g.
#Produces(MediaType.APPLICATION_JSON)
public abstract class JsonMessageBodyWriterAdapter<T> implements MessageBodyWriter<T> { ...
}
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
#Path("xxx")
public class XxxBs {
#POST
public void create(#NotNull final XxxDO xxxDo) throws ResponseException {
// do something
}
}

Easymock with Powermock error

I am using Easymock with Powermock. When I try to test, this is the error I get.
java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler#959a1da3 failed.
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:95)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:298)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
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:288)
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:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
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:123)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
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.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)
Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class java.lang.String
at org.easymock.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at org.easymock.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
at org.easymock.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at org.easymock.cglib.proxy.Enhancer.createHelper(Enhancer.java:377)
at org.easymock.cglib.proxy.Enhancer.createClass(Enhancer.java:317)
at org.easymock.internal.ClassProxyFactory.createProxy(ClassProxyFactory.java:175)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:113)
at org.easymock.internal.MocksControl.createMock(MocksControl.java:98)
at org.easymock.EasyMock.mock(EasyMock.java:128)
at org.easymock.EasyMock.createMock(EasyMock.java:259)
at org.easymock.internal.Injector.createMocksForAnnotations(Injector.java:130)
at org.easymock.internal.Injector.injectMocks(Injector.java:66)
at org.easymock.EasyMockSupport.injectMocks(EasyMockSupport.java:528)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620)
at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1899)
at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:801)
at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:781)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:71)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:93)
... 24 more
And my class looks like this.
public String renameOrDeleteDirectory(String Directory, String dirExtn, (short) x){
File workDir = new File(Directory);
String OrigDir = null;
File origDir =null;
boolean renamed = false;
try {
if (null != Directory && Directory.length() > 0 ) {
if(new File(Directory).list().length == 0){
new File(Directory).delete();
}
My test case is like this...
#RunWith(PowerMockRunner.class)
#PrepareForTest(value={Utilities.class, File.class})
public class dirTest1 {
#Test
public void testRenameOrDeleteDirectory1() throws Exception {
mockStatic(File.class);
expectNew(File.class, "C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready").andReturn(workDir);
expect(workDir.list().length == 0).andReturn(true);
expect(workDir.delete()).andReturn(true);
// expect(null != Directory && Directory.length() > 0).andReturn(true);
// expect(new File(Directory).list().length == 0).andReturn(true);
// expect(new File(Directory).delete()).andReturn(true);
PowerMock.replay(File.class, workDir);
Utilities utilities = new Utilities();
utilities.renameOrDeleteDirectory("C:\\Users\\Desktop\\Docs\\Docs2017_03_07_14_docready", "_Ready", (short) 0);
PowerMock.verify(File.class, workDir);
}
}
Hint: your real problem is that you are using new all over the place within your production code. That simply creates hard to test code. And thus you end up looking for PowerMock.
Alternatively, you could create a simple
class FileFactory {
File getFileFor(String fileName) { ...
and use that as field within your class. Now, when you need a File for a certain string, you use that FileFactory instance.
The really nice thing here: that FileFactory can be mocked easily.
So instead of needing PowerMock and all its quirks, you could
improve your design
do full unit-testing ... just with frameworks like EasyMock or Mockito
I solved this error.
It was caused because I was mocking a string along with other mocks.

Junit/PowerMockito : java.lang.NoClassDefFoundError: javassist.CannotCompileException

Getting below exception while running junit test:
java.lang.NoClassDefFoundError: javassist.CannotCompileException
at java.lang.J9VMInternals.verifyImpl(Native Method)
at java.lang.J9VMInternals.verify(J9VMInternals.java:85)
at java.lang.J9VMInternals.initialize(J9VMInternals.java:162)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createDefaultExtraMockTransformers(AbstractTestSuiteChunkerImpl.java:257)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.chunkClass(AbstractTestSuiteChunkerImpl.java:169)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.<init>(AbstractTestSuiteChunkerImpl.java:96)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.<init>(AbstractTestSuiteChunkerImpl.java:89)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:49)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:32)
at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:56)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:39)
at java.lang.reflect.Constructor.newInstance(Constructor.java:527)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:31)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:24)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:29)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:57)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.<init>(JUnit4TestReference.java:32)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.<init>(JUnit4TestClassReference.java:25)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:41)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:31)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
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)
Caused by: java.lang.ClassNotFoundException: javassist.CannotCompileException
at java.net.URLClassLoader.findClass(URLClassLoader.java:434)
at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:665)
at java.lang.ClassLoader.loadClass(ClassLoader.java:644)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:358)
at java.lang.ClassLoader.loadClass(ClassLoader.java:627)
... 28 more
I have below two classes :
public class Employee {
public static int count() {
throw new UnsupportedOperationException();
}
}
public class EmployeeService {
public int getEmployeeCount() {
return Employee.count();
}
}
I wrote below test class to test the EmployeeService :
#RunWith(PowerMockRunner.class)
#PrepareForTest(Employee.class)
public class EmployeeServiceTest {
#Test
public void testGetEmployeeCount() {
PowerMockito.mockStatic(Employee.class);
PowerMockito.when(Employee.count()).thenReturn(900);
EmployeeService employeeService = new EmployeeService();
Assert.assertEquals(900,employeeService.getEmployeeCount());
}
}
Dependencies used for mockito and power mockito are as follows:
mockito-all-1.10.19.jar
powermock-mockito-1.6.2-full.jar
objenesis-2.1.jar
cglib-nodep-2.2.2.jar
To resolve the exception I also added javassist-3.12.0.GA-sources.jar to the classpath but it did not help.
But getting exception as shown above. Kindly help me out.
javassist-3.12.0.GA-sources.jar is like to contain sources (java text files), not compiled java class files. Use jar tf javassist-3.12.0.GA-sources.jar to investigate and make sure you include a jar containing .class files.

Error in Parameterised test cases in Junit

I am trying to write a parameterized test case in JUnit. My code looks like this:
#RunWith(Parameterized.class)
#PrepareForTest({AR9DirectDebitFileWriterCustomization.class})
public class AR9DirectDebitFileWriterCustomizationTest2 extends AR3BasicUnitTest {
private DirectDebitExtractDetRec mockObj;
private ARApplicationContext mockAppCon;
private AR9DirectDebitFileWriterCustomization spyObj = null;
AccountDBViewData mockdbData;
AccountDBView mockdbView;
SearchInvoicesDBViewData[] mocksearchInvdbviewdatarr = new SearchInvoicesDBViewData[1];
#Before
public void setUp() throws Exception {
AR9DirectDebitFileWriterCustomization ar9Obj = new AR9DirectDebitFileWriterCustomization(mockdbView, mocksearchInvdbviewdatarr, mockdbData);
spyObj = PowerMockito.spy(ar9Obj);
}
public AR9DirectDebitFileWriterCustomizationTest2(DirectDebitExtractDetRec mockObj_from_collection, ARApplicationContext mockAppCon_from_collection) {
this.mockObj = mockObj_from_collection;
this.mockAppCon = mockAppCon_from_collection;
}
#Parameterized.Parameters
public static Collection<Object[]> getparameters() throws ACMException{
return Arrays.asList(new Object[][]{
{mock(DirectDebitExtractDetRec.class),mock(ARApplicationContext.class)}
});
}
#Test
#Parameters
public final void testAddFileRecordCustObjectARApplicationContext( ) throws Exception {
.....SOME CODE
}
Whenever I right click on the testAddFileRecordCustObjectARApplicationContext function and run it as Junit test I get an initialization error :
java.lang.Exception: No tests found matching Method
testAddFileRecordCustObjectARApplicationContext(amdocs.ar.customizationexits.handlers.helpers.AR9DirectDebitFileWriterCustomizationTest2)
from org.junit.internal.requests.ClassRequest#3fa50b at
org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:37)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.(JUnit4TestReference.java:33)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestMethodReference.(JUnit4TestMethodReference.java:25)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:54)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
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)
After looking for several hours on internet about this issue I could not find anything meaningful. In this scenario I am using spy and powerMocktio Functionality as well.I am not sure what is the root of this error .
And interesting thing is when I run it without using Parameterised test ,it works perfectly fine.
I had very similar error:
No tests found matching data with any parameter from...
According to my observations, it is caused by another strange error:
Unable to mock class ... due to a missing dependency
Only the first I see when I run the test, and the second, when I debug it. According to https://stackoverflow.com/a/23788935/715269,
https://stackoverflow.com/a/25659518/715269, it is the bug connected to classpath reading. The problem disappears, when we upgrade JMockit to higher versions.