Mockito cannot mock JdbcTemplate - junit

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.

Related

JUnit showing erro java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter

# Junit not working giving error #
Tried testing basic add operation using Junit its showing this error on my mac
# AddTest.java #
import static org.junit.Assert.*;
import org.junit.Test;
public class AddTest {
#Test
public void Addtest() {
MyJUnitClass junit = new MyJUnitClass();
int result = junit.add(100, 200);
assertEquals(300, result);
}
}
# MyJunitClass #
public class MyJUnitClass {
public int add(int a, int b) {
return a+b;
}
public String conCat(String a, String b) {
return a+b;
}
}
java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:332)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadTestLoaderClass(RemoteTestRunner.java:380)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:370)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:365)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:309)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:224)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:208)
Caused by: java.lang.ClassNotFoundException: org.junit.runner.manipulation.Filter
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 8 more
This is the error I am getting while running I have placed the JUnit 4.jar file libraries in buildpath. My I am able to access all the functions from JUnit jar file but when I run the JUnit test I get Failure error and this message in console.
You should try "add library", and then choosing JUnit, not adding a jar directly !
Good luck :)

Powermock - Unable to mock ScheduledExecutorService

I am unable to mock the ScheduledExcecutorService. Unsure where I am making the mistake. One weird part about the exception is "Cannot find method schedule in Object hierarchy", why is it trying to find method in Object class instead of ScheduledExecutorService?
Any help would be appreciated. Thanks in advance.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ScheduledExecutorService.class, GenericCache.class, ConfigurationDAO.class, ScheduledFuture.class })
#PowerMockIgnore("javax.management.*")
public class CacheManagerTestCase {
// Fields
#Mock
private ScheduledExecutorService mockScheduledExecutorService;
#Mock
private ScheduledFuture scheduledFutureMock;
// Within Test method
when(mockScheduledExecutorService
.schedule(any(Runnable.class), anyLong(), eq(TimeUnit.SECONDS)))
.thenReturn(scheduledFutureMock);
When running the above code, following exception is thrown
org.powermock.reflect.exceptions.MethodNotFoundException: No methods matching the name(s) schedule were found in the class hierarchy of class java.lang.Object.
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1720)
at org.powermock.reflect.internal.WhiteboxImpl.getMethods(WhiteboxImpl.java:1745)
at org.powermock.reflect.internal.WhiteboxImpl.getBestMethodCandidate(WhiteboxImpl.java:983)
at org.powermock.core.MockGateway$MockInvocation.findMethodToInvoke(MockGateway.java:317)
at org.powermock.core.MockGateway$MockInvocation.init(MockGateway.java:356)
at org.powermock.core.MockGateway$MockInvocation.<init>(MockGateway.java:307)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:142)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:125)
at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
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:606)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 3 recorded:
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
-> at CacheManagerTestCase.testPeriodicRefreshPropertyFalse(CacheManagerTestCase.java:82)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

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.

InetAddress static method doesn't mock with PowerMockito

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})

Spring Security: Java configuration with data source

Not so long ago Spring presented a java based configuration for the Spring Security module. I try to migrate from XML to Java configuration.
Here is my test project: https://github.com/Fruzenshtein/security-spr
pom.xml was updated:
spring.version = 3.2.4.RELEASE
spring.security.version = 3.1.4.RELEASE
...
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-javaconfig</artifactId>
<version>1.0.0.M1</version>
</dependency>
...
<repository>
<id>repository.springsource.milestone</id>
<name>SpringSource Milestone Repository</name>
<url>http://repo.springsource.org/milestone</url>
</repository>
Then I have added a new java config class instead of spring-security.xml
package com.sprsec.init;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.sprsec.service.CustomUserDetailsService;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.userDetailsService(new CustomUserDetailsService())
.authorizeUrls()
.antMatchers("/sec/moderation.html").hasRole("MODERATOR")
.antMatchers("/admin/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/user-login.html")
.defaultSuccessUrl("/success-login.html")
.failureUrl("/error-login.html")
.permitAll()
.and()
.logout()
.logoutSuccessUrl("/index.html");
}
}
After that I changed my Initializaer.class to:
package com.sprsec.init;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class Initializer extends
AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Remark:
spring-security.xml was deleted
A line of code #ImportResource("classpath:spring-security.xml") was deleted in WebAppConfig.java
Filter declaration in web.xml was removed
When I try to run the application on a server I get:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webAppConfig': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor' defined in class path resource [org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration.transactionAdvisor()] threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor.setAdvice(Lorg/aopalliance/aop/Advice;)V
Can someone give an advice what can be a reason of this?
You are probably running into some dependency conflict. Run maven dependency:tree to figure out which dependencies are used and find conflicting ones. Also the use of the maven-enforcer-plugin might help.
Looking at your sample project you are using Spring 3.1.3 and the same for Spring Security, you want to have seperate properties for spring and spring security.
<properties>
<hibernate.version>4.1.7.Final</hibernate.version>
<mysql.connector.version>5.1.21</mysql.connector.version>
<slf4j.version>1.6.6</slf4j.version>
<spring.version>3.2.4.RELEASE</spring.version>
<spring.security.version>3.1.4.RELEASE<spring.security.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
As for Spring Security you might want to try out the new 3.2.0.RC1 as that already includes the new spring security javaconfig with improvements and some convenience superclasses.
A final note on your configuration, as that is flawed, you are duplicating your bean instances as you are loading the same configuration twice (duplicating your whole configuration), both the ContextLoaderListener and DispatcherServlet use the WebAppConfig for configuration. This could effectively render your security useless.
Submitted a pull request which should give you some pointers on how to fix the issue at hand.