We're writing unit tests for a Jersey Java REST service using PowerMock. We have to use PowerMock because we use numerous static methods in a legacy system. We're using PowerMock with EasyMock. Whenever we try to inherit from JerseyTest, the whole framework fails.
It's a gradle based project, and the pertinent build.gradle lines are below.
testCompile 'junit:junit:4.12'
testCompile group: 'org.easymock', name: 'easymock', version: '3.5.1'
testCompile group: 'org.easymock', name: 'easymockclassextension', version: '3.2'
testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.3'
testCompile group: 'org.powermock', name: 'powermock-api-easymock', version: '1.7.3'
We have a few EasyMock unit tests up and running, so we know our imports are working correctly. The problem is that since we're testing a Jersey web service, our unit tests inherit from JerseyTest. Writing a PowerMock unit test without inheriting from JerseyTest works fine. But when we try to inherit from JerseyTest, it all falls apart. Google failed us (apparently no one else who has written a Jersey web service has tried using PowerMock).
What we do is fairly straight-forward. This works:
#RunWith(PowerMockRunner.class)
public class PowerMockTest {
private final static String TARGET = "ourwebservice/";
#Test
public void testConfigurationGet() {
// do stuff, but no Jersey web service calls
}
}
Changing the class declaraction to inherit from JerseyTest, however:
public class PowerMockTest extends JerseyTest {
And we get a complete failure. We're using Eclipse as our IDE, and this is the error that displays in the JUnit window:
initializationError (0.000 s)
The Failure Trace window gives more details:
java.lang.VerifyError: Inconsistent stackmap frames at branch target 38
Exception Details:
Location:
com/ourcompany/ourproduct/rest/PowerMockTest.<init>()V #38: aload_1
Reason:
Type uninitializedThis (current frame, locals[1]) is not assignable to 'com/ourcompany/ourproduct/rest/PowerMockTest' (stack map, locals[1])
Current Frame:
bci: #24
flags: { flagThisUninit }
locals: { uninitializedThis, uninitializedThis, top, 'java/lang/Object' }
stack: { 'java/lang/Object', 'java/lang/Object' }
Stackmap Frame:
bci: #38
flags: { flagThisUninit }
locals: { uninitializedThis, 'com/ourcompany/ourproduct/rest/PowerMockTest' }
stack: { }
Bytecode:
0x0000000: 2a4c 1211 b800 1703 bd00 1912 1ab8 001e
0x0000010: b800 244e 2db2 0028 a500 0e2a 01c0 002a
0x0000020: b700 2ea7 0009 2bb7 0030 0157 a700 0301
0x0000030: 3a05 2ab8 0036 b1
Stackmap Table:
append_frame(#38,Object[#14])
chop_frame(#44,1)
same_frame(#47)
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetPublicMethods(Class.java:2902)
at java.lang.Class.getMethods(Class.java:1615)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.getTestMethods(PowerMockJUnit44RunnerDelegateImpl.java:109)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.<init>(PowerMockJUnit44RunnerDelegateImpl.java:85)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl.<init>(PowerMockJUnit47RunnerDelegateImpl.java:42)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit49RunnerDelegateImpl.<init>(PowerMockJUnit49RunnerDelegateImpl.java:25)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:172)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.createDelegatorFromClassloader(JUnit4TestSuiteChunkerImpl.java:48)
at org.powermock.tests.utils.impl.AbstractTestSuiteChunkerImpl.createTestDelegators(AbstractTestSuiteChunkerImpl.java:108)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.<init>(JUnit4TestSuiteChunkerImpl.java:71)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.<init>(AbstractCommonPowerMockRunner.java:36)
at org.powermock.modules.junit4.PowerMockRunner.<init>(PowerMockRunner.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:87)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:73)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:46)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
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)
We can't even step into the method to debug it; it fails before that (note, the test doesn't even actually do anything yet; we're just trying to get things set up first).
Anyone have any idea what's going on? Do we have some sort of configuration error? Do we have to switch to Mockito?
Related
I am trying to build a native-image for Micronaut project for AWS Lambda, but it is not going through. When I run the build using ./gradlew clean buildNativeLambda -Pmicronaut.runtime=lambda command, the memory and CPU usage shoots to 100% and after 30-40 mins, it fails with below exception (truncated):
=== Image generator watchdog detected no activity. This can be a sign of a deadlock during image building. Dumping all stack traces. Current time: Mon Oct 03 10:48:30 UTC 2022
"main" Id=1 in RUNNABLE
at app//com.oracle.graal.pointsto.flow.OffsetStoreTypeFlow$AbstractUnsafeStoreTypeFlow.handleUnsafeAccessedFields(OffsetStoreTypeFlow.java:244)
at app//com.oracle.graal.pointsto.flow.OffsetStoreTypeFlow$UnsafeStoreTypeFlow.onObservedUpdate(OffsetStoreTypeFlow.java:292)
at app//com.oracle.graal.pointsto.flow.TypeFlow.update(TypeFlow.java:552)
at app//com.oracle.graal.pointsto.PointsToAnalysis$1.run(PointsToAnalysis.java:631)
at app//com.oracle.graal.pointsto.util.CompletionExecutor.executeCommand(CompletionExecutor.java:193)
at app//com.oracle.graal.pointsto.util.CompletionExecutor.lambda$executeService$0(CompletionExecutor.java:177)
at app//com.oracle.graal.pointsto.util.CompletionExecutor$$Lambda$677/0x00000007c3273440.run(Unknown Source)
at java.base#11.0.15/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
at java.base#11.0.15/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base#11.0.15/java.util.concurrent.ForkJoinPool.awaitQuiescence(ForkJoinPool.java:2984)
at app//com.oracle.graal.pointsto.util.CompletionExecutor.complete(CompletionExecutor.java:243)
at app//com.oracle.graal.pointsto.PointsToAnalysis.doTypeflow(PointsToAnalysis.java:688)
at app//com.oracle.graal.pointsto.PointsToAnalysis.finish(PointsToAnalysis.java:676)
at app//com.oracle.graal.pointsto.PointsToAnalysis.runAnalysis(PointsToAnalysis.java:732)
at app//com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:723)
at app//com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:558)
at app//com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:515)
at app//com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:407)
at app//com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:585)
at app//com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128)
at app//com.oracle.svm.hosted.NativeImageGeneratorRunner$JDK9Plus.main(NativeImageGeneratorRunner.java:615)
"Reference Handler" Id=2 in RUNNABLE
at java.base#11.0.15/java.lang.ref.Reference.processPendingReferences(Reference.java:261)
at java.base#11.0.15/java.lang.ref.Reference$ReferenceHandler.run(Reference.java:213)
"Finalizer" Id=3 in WAITING on lock=java.lang.ref.ReferenceQueue$Lock#16974940
at java.base#11.0.15/java.lang.Object.wait(Native Method)
at java.base#11.0.15/java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:155)
at java.base#11.0.15/java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:176)
at java.base#11.0.15/java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:170)
"Signal Dispatcher" Id=4 in RUNNABLE
"JVMCI-native CompilerThread0" Id=6 in RUNNABLE
"Common-Cleaner" Id=9 in RUNNABLE
at java.base#11.0.15/java.lang.invoke.MethodHandleNatives.clearCallSiteContext(Native Method)
at java.base#11.0.15/java.lang.invoke.MethodHandleNatives$CallSiteContext.run(MethodHandleNatives.java:92)
at java.base#11.0.15/jdk.internal.ref.CleanerImpl$PhantomCleanableRef.performCleanup(CleanerImpl.java:186)
at java.base#11.0.15/jdk.internal.ref.PhantomCleanable.clean(PhantomCleanable.java:133)
at java.base#11.0.15/jdk.internal.ref.CleanerImpl.run(CleanerImpl.java:150)
at java.base#11.0.15/java.lang.Thread.run(Thread.java:829)
at java.base#11.0.15/jdk.internal.misc.InnocuousThread.run(InnocuousThread.java:161)
"native-image pid watcher" Id=13 in TIMED_WAITING on lock=java.util.TaskQueue#1850a5e2
at java.base#11.0.15/java.lang.Object.wait(Native Method)
at java.base#11.0.15/java.util.TimerThread.mainLoop(Timer.java:553)
at java.base#11.0.15/java.util.TimerThread.run(Timer.java:506)
"Libgraal MBean Registration" Id=22 in TIMED_WAITING
at java.base#11.0.15/java.lang.Thread.sleep(Native Method)
at platform/jdk.internal.vm.compiler.management/org.graalvm.compiler.hotspot.management.Factory.run(Factory.java:111)
"ForkJoinPool.commonPool-worker-5" Id=24 in TIMED_WAITING on lock=java.util.concurrent.ForkJoinPool#18cbf3e3
at java.base#11.0.15/jdk.internal.misc.Unsafe.park(Native Method)
at java.base#11.0.15/java.util.concurrent.locks.LockSupport.parkUntil(LockSupport.java:275)
at java.base#11.0.15/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1619)
at java.base#11.0.15/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
"ForkJoinPool.commonPool-worker-15" Id=29 in WAITING on lock=java.util.concurrent.ForkJoinPool#18cbf3e3
at java.base#11.0.15/jdk.internal.misc.Unsafe.park(Native Method)
at java.base#11.0.15/java.util.concurrent.locks.LockSupport.park(LockSupport.java:194)
at java.base#11.0.15/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1628)
at java.base#11.0.15/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Below are the dependencies in build.gradle:
dependencies {
annotationProcessor('io.micronaut:micronaut-inject-java')
annotationProcessor("io.micronaut.data:micronaut-data-processor")
annotationProcessor("io.micronaut:micronaut-http-validation")
implementation("io.micronaut:micronaut-http-client")
implementation("io.micronaut:micronaut-jackson-databind")
implementation("jakarta.annotation:jakarta.annotation-api")
runtimeOnly("ch.qos.logback:logback-classic")
// runtimeOnly('org.slf4j:log4j-over-slf4j:2.0.2')
implementation("io.micronaut:micronaut-validation")
implementation("io.micronaut.aws:micronaut-function-aws-custom-runtime")
implementation("io.micronaut.data:micronaut-data-hibernate-jpa")
implementation("io.micronaut.sql:micronaut-jdbc-hikari")
runtimeOnly("mysql:mysql-connector-java")
compileOnly("org.graalvm.nativeimage:svm")
implementation("io.micronaut.aws:micronaut-function-aws")
implementation("io.micronaut.aws:micronaut-function-aws-custom-runtime")
implementation group: 'org.json', name: 'json', version: "${orgJsonVersion}"
implementation group: 'org.apache.poi', name: 'poi', version: "${poiVersion}"
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: "${poiVersion}"
implementation group: 'org.apache.commons', name: 'commons-lang3', version: "${apacheCommons}"
implementation group: 'com.google.code.gson', name: 'gson', version: "${googleGson}"
// implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: "${springValidation}"
implementation group: 'org.eclipse.persistence', name: 'eclipselink', version: "${eclipseLink}"
// compileOnly group: 'javax.servlet', name: 'servlet-api', version: "${servletApi}"
implementation("org.apache.velocity:velocity:${velocity}") {
exclude group: 'log4j', module: 'log4j'
}
implementation("org.apache.velocity:velocity-tools:${velocityTools}") {
exclude group: 'log4j', module: 'log4j'
}
implementation group: 'org.apache.kafka', name: 'kafka-clients', version: "${kafkaClient}"
implementation group: 'com.google.guava', name: 'guava', version: "${googleGuava}"
}
Below are the build configurations in build.gradle:
tasks.named("dockerfileNative") {
args(
"-XX:MaximumHeapSizePercent=80",
"-Dio.netty.allocator.numDirectArenas=0",
"-Dio.netty.noPreferDirect=true"
)
}
graalvmNative.binaries.all {
buildArgs.add("--no-server -J-Xmx12g -J-Xms4g")
}
I tried to playing with graalvmNative.binaries.all arguments, but nothing seems to be working.
System configuration:
RAM: 16GB
CPU: i5 11th Gen
OS: Windows 10
I am not sure what is going wrong here, and also I am not sure like what are the resource requirements to build the Graalvm native-image. Any help on this please.
I am trying to do a POC of Flink State Schema Evolution. I am using Flink 1.15.0 and Java 11.
I tried to create 3 data classes - one for each serialization type:
io.peleg.kryo.User - Uses java.time.Instant class which I know is not supported for POJO serialization in Flink.
io.peleg.pojo.User - Uses only classic wrapped primitives - Integer, Long, String. The getters, setters and constructors are generated using Lombok.
io.peleg.avro.User - Generated from Avro schema using Avro Maven Plugin.
For each class I wrote a stream job that uses a time window to buffer elements and turn them into a list.
For each class I tried to do the following:
Run a job
Stop with savepoint
Add a field to the data class
Submit using savepoint
For all data classes the submit with savepoint failed with this exception:
java.lang.Exception: Exception while creating StreamOperatorStateContext.
at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:255)
at org.apache.flink.streaming.api.operators.AbstractStreamOperator.initializeState(AbstractStreamOperator.java:268)
at org.apache.flink.streaming.runtime.tasks.RegularOperatorChain.initializeStateAndOpenOperators(RegularOperatorChain.java:106)
at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreGates(StreamTask.java:700)
at org.apache.flink.streaming.runtime.tasks.StreamTaskActionExecutor$1.call(StreamTaskActionExecutor.java:55)
at org.apache.flink.streaming.runtime.tasks.StreamTask.restoreInternal(StreamTask.java:676)
at org.apache.flink.streaming.runtime.tasks.StreamTask.restore(StreamTask.java:643)
at org.apache.flink.runtime.taskmanager.Task.runWithSystemExitMonitoring(Task.java:948)
at org.apache.flink.runtime.taskmanager.Task.restoreAndInvoke(Task.java:917)
at org.apache.flink.runtime.taskmanager.Task.doRun(Task.java:741)
at org.apache.flink.runtime.taskmanager.Task.run(Task.java:563)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: org.apache.flink.util.FlinkException: Could not restore keyed state backend for WindowOperator_3983d6bb2f0a45b638461bc99138f22f_(2/2) from any of the 1 provided restore options.
at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:160)
at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.keyedStatedBackend(StreamTaskStateInitializerImpl.java:346)
at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.streamOperatorStateContext(StreamTaskStateInitializerImpl.java:164)
... 11 more
Caused by: org.apache.flink.runtime.state.BackendBuildingException: Failed when trying to restore heap backend
at org.apache.flink.runtime.state.heap.HeapKeyedStateBackendBuilder.restoreState(HeapKeyedStateBackendBuilder.java:172)
at org.apache.flink.runtime.state.heap.HeapKeyedStateBackendBuilder.build(HeapKeyedStateBackendBuilder.java:106)
at org.apache.flink.runtime.state.hashmap.HashMapStateBackend.createKeyedStateBackend(HashMapStateBackend.java:143)
at org.apache.flink.runtime.state.hashmap.HashMapStateBackend.createKeyedStateBackend(HashMapStateBackend.java:74)
at org.apache.flink.runtime.state.StateBackend.createKeyedStateBackend(StateBackend.java:140)
at org.apache.flink.streaming.api.operators.StreamTaskStateInitializerImpl.lambda$keyedStatedBackend$1(StreamTaskStateInitializerImpl.java:329)
at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.attemptCreateAndRestore(BackendRestorerProcedure.java:168)
at org.apache.flink.streaming.api.operators.BackendRestorerProcedure.createAndRestore(BackendRestorerProcedure.java:135)
... 13 more
Caused by: com.esotericsoftware.kryo.KryoException: java.lang.IndexOutOfBoundsException: Index 83 out of bounds for length 3
Serialization trace:
favoriteColor (io.peleg.avro.User)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:125)
at com.esotericsoftware.kryo.serializers.FieldSerializer.read(FieldSerializer.java:528)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:761)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:116)
at com.esotericsoftware.kryo.serializers.CollectionSerializer.read(CollectionSerializer.java:22)
at com.esotericsoftware.kryo.Kryo.readClassAndObject(Kryo.java:761)
at org.apache.flink.api.java.typeutils.runtime.kryo.KryoSerializer.deserialize(KryoSerializer.java:402)
at org.apache.flink.runtime.state.heap.HeapSavepointRestoreOperation.readKVStateData(HeapSavepointRestoreOperation.java:219)
at org.apache.flink.runtime.state.heap.HeapSavepointRestoreOperation.readKeyGroupStateData(HeapSavepointRestoreOperation.java:149)
at org.apache.flink.runtime.state.heap.HeapSavepointRestoreOperation.restore(HeapSavepointRestoreOperation.java:125)
at org.apache.flink.runtime.state.heap.HeapSavepointRestoreOperation.restore(HeapSavepointRestoreOperation.java:57)
at org.apache.flink.runtime.state.heap.HeapKeyedStateBackendBuilder.restoreState(HeapKeyedStateBackendBuilder.java:169)
... 20 more
Caused by: java.lang.IndexOutOfBoundsException: Index 83 out of bounds for length 3
at java.base/jdk.internal.util.Preconditions.outOfBounds(Unknown Source)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Unknown Source)
at java.base/jdk.internal.util.Preconditions.checkIndex(Unknown Source)
at java.base/java.util.Objects.checkIndex(Unknown Source)
at java.base/java.util.ArrayList.get(Unknown Source)
at com.esotericsoftware.kryo.util.MapReferenceResolver.getReadObject(MapReferenceResolver.java:42)
at com.esotericsoftware.kryo.Kryo.readReferenceOrNull(Kryo.java:805)
at com.esotericsoftware.kryo.Kryo.readObjectOrNull(Kryo.java:728)
at com.esotericsoftware.kryo.serializers.ObjectField.read(ObjectField.java:113)
... 31 more
I expected this exception would be thrown for io.peleg.kryo.User since Flink does not support state schema evolution for Kryo serialized classes.
But it seems to me like for all classes it ended up using the Kryo serializer instead of the POJO or Avro serializers.
I ran the job on a Flink cluster I spun up using docker compose:
version: "2.2"
services:
jobmanager:
image: flink:latest
ports:
- "8081:8081"
command: jobmanager
environment:
- |
FLINK_PROPERTIES=
jobmanager.rpc.address: jobmanager
taskmanager:
image: flink:latest
depends_on:
- jobmanager
command: taskmanager
scale: 1
environment:
- |
FLINK_PROPERTIES=
jobmanager.rpc.address: jobmanager
taskmanager.numberOfTaskSlots: 2
My entire code is public on GitHub here.
What I would like to achieve is succusfuly running a job from a savepoint of an older version of a POJO with less/more fields.
I did an experiment with this POJO class:
public class Event {
public long id;
public String data;
public Instant timestamp;
public Event() {}
public Event(final long id, final String data, final Instant timestamp ) {
this.id = id;
this.data = data;
this.timestamp = timestamp;
}
...
}
The image below is from the IntelliJ debugger. As you can see, Flink supplied an InstantSerializer, and is using its POJOSerializer for this Event class.
I'm not sure where you went wrong, but you can use
env.getConfig().disableGenericTypes();
to disable the Kyro fallback, which should help with these experiments.
I'm writing android unit tests with Robolectric. When I run my tests currently, I keep getting the above error.
I have looked at and tried tons of suggested solutions from here, but none of them have resolved this error.
So far I have looked at the dependency tree and I can see two versions of guava being used:
+--- com.google.guava:guava-jdk5:13.0#jar
+--- com.google.guava:guava:27.0.1-android#jar
After noticing this, I have then tried to:
exclude the first dependency
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:4.0.1'
classpath ('org.robolectric:robolectric:4.1') {
exclude group: 'com.google.guava', module: 'guava-jdk5'
}
}
}
upgrade the guava version to the latest
api 'com.google.guava:guava:27.0.1-android'
This is what the error looks like:
java.lang.NoSuchMethodError: com.google.common.base.CharMatcher.whitespace()Lcom/google/common/base/CharMatcher;
at org.robolectric.res.StringResources.processStringResources(StringResources.java:19)
at org.robolectric.res.StaxValueLoader.onEnd(StaxValueLoader.java:33)
at org.robolectric.res.StaxDocumentLoader.doParse(StaxDocumentLoader.java:66)
at org.robolectric.res.StaxDocumentLoader.loadResourceXmlFile(StaxDocumentLoader.java:30)
at org.robolectric.res.DocumentLoader.loadFile(DocumentLoader.java:48)
at org.robolectric.res.DocumentLoader.load(DocumentLoader.java:27)
at org.robolectric.res.ResourceTableFactory.parseResourceFiles(ResourceTableFactory.java:149)
at org.robolectric.res.ResourceTableFactory.lambda$newFrameworkResourceTable$0(ResourceTableFactory.java:26)
at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:50)
at org.robolectric.res.ResourceTableFactory.newFrameworkResourceTable(ResourceTableFactory.java:12)
at org.robolectric.internal.SdkEnvironment.getSystemResourceTable(SdkEnvironment.java:35)
at org.robolectric.ApkLoader.getSystemResourceTable(ApkLoader.java:32)
at org.robolectric.android.internal.ParallelUniverse.injectResourceStuffForLegacy(ParallelUniverse.java:252)
at org.robolectric.android.internal.ParallelUniverse.setUpApplicationState(ParallelUniverse.java:126)
at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:379)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:252)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:130)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:42)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:84)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
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)
And this is my Test class currently:
#RunWith(RobolectricTestRunner.class)
public class MyTestClass {
MyTestFragment myTestFragment;
#Test
public void fragmentIsNotNull() throws Exception{
myTestFragment = MyTestFragment.newInstance();
assertNotNull(myTestFragment);
}
}
I would appreciate any help with this.
Thanks.
I have finally been able to get this to work by following the answer given here on SO from someone with a similar problem.
The issue was two conflicting guava dependencies as I pointed above.
+--- com.google.guava:guava-jdk5:13.0#jar
+--- com.google.guava:guava:27.0.1-android#jar
This is what I had tried before, to exclude guava,
configurations {
all*.exclude group: 'com.google.guava', module:'guava-jdk5'
}
But the guava-jdk-5 dependency was still being maintained.
So I finally added this to my gradle file instead:
compile('com.google.guava:guava-jdk5:17.0') { force = true }
This is what finally solved the bug.
I am just starting to learn Grails testing and I tried to write my first grails test.For this, I created a fresh grails project and created a controller named com.rahulserver.SomeController:
package com.rahulserver
class SomeController {
def index() { }
def someAction(){
}
}
When I created this controller, grails automatically created a com.rahulserver.SomeControllerSpec under test/unit folder.
Here is my SomeControllerSpec.groovy:
package com.rahulserver
import grails.test.mixin.TestFor
import spock.lang.Specification
/**
* See the API for {#link grails.test.mixin.web.ControllerUnitTestMixin} for usage instructions
*/
#TestFor(SomeController)
class SomeControllerSpec extends Specification {
def setup() {
}
def cleanup() {
}
void testSomeAction() {
assert 1==1
}
}
When I right click this class, and run this test, I get following:
Testing started at 5:21 PM ...
|Loading Grails 2.4.3
|Configuring classpath
.
|Environment set to test
....................................
|Running without daemon...
..........................................
|Compiling 1 source files
.
|Running 1 unit test...|Running 1 unit test... 1 of 1
--Output from initializationError--
Failure: |
initializationError(org.junit.runner.manipulation.Filter)
|
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
java.lang.Exception: No tests found matching grails test target pattern filter from org.junit.runner.Request$1#1f0f9da5
at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:35)
at org.junit.runner.JUnitCore.run(JUnitCore.java:138)
|Completed 1 unit test, 1 failed in 0m 0s
.Tests FAILED
|
- view reports in D:\115Labs\grailsunittestdemo\target\test-reports
Error |
Forked Grails VM exited with error
Process finished with exit code 1
So why is it failing?
EDIT
I am using grails 2.4.3
The unit tests are defined with Spock by default:
void testSomeAction() {
assert 1==1
}
Should be written as:
void "Test some action"() {
expect:
1==1
}
See http://spockframework.github.io/spock/docs/1.0/index.html
I am trying to build a RESTful WebService project with gradle tool. But build is failing. The console is giving following output.
C:\Users\bob\Downloads\gs-rest-service-master\gs-rest-service-master\complete>gradle build
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring root project 'complete'.
> Could not resolve all dependencies for configuration ':classpath'.
> Could not resolve org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RC4.
Required by:
:complete:unspecified
> Could not GET 'http://repo.spring.io/libs-snapshot/org/springframework/boot/spring- boot-gradle-plugin/1.0.0.RC4/spring-boot-gradle-plugin-1.0.0.RC4.pom'.
> Connection to http://repo.spring.io refused
> java.lang.NullPointerException (no error message)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
And when I give the command
gradle build --stacktrace
Getting the following stacktrace:
Caused by: org.gradle.api.internal.artifacts.ivyservice.ModuleVersionResolveException: Could not resolve org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RC4.
Required by:
:complete:unspecified
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.r esolve(RepositoryChainDependencyResolver.java:72)
at org.gradle.api.internal.artifacts.ivyservice.clientmodule.ClientModuleResolver.resolve(Clie ntModuleResolver.java:35)
at org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectDependencyResolver.resolv e(ProjectDependencyResolver.java:49)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.LazyDependencyToModuleResolver$AbstractVersionResolveResult.resolve(LazyDependencyToModuleResolver.java:69)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder$ModuleVersionResolveState.resolve(DependencyGraphBuilder.java:655)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder$ModuleVersionResolveState.getMetaData(DependencyGraphBuilder.java:666)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder$DependencyEdge.calculateTargetConfigurations(DependencyGraphBuilder.java:340)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder$DependencyEdge.attachToTargetConfigurations(DependencyGraphBuilder.java:314)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder.traverseGraph(DependencyGraphBuilder.java:130)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DependencyGraphBuilder.resolve(DependencyGraphBuilder.java:70)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver$1.execute(DefaultDependencyResolver.java:116)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver$1.execute(DefaultDependencyResolver.java:82)
at org.gradle.internal.Transformers$3.transform(Transformers.java:131)
at org.gradle.api.internal.artifacts.ivyservice.DefaultIvyContextManager.withIvy(DefaultIvyContextManager.java:61)
at org.gradle.api.internal.artifacts.ivyservice.DefaultIvyContextManager.withIvy(DefaultIvyContextManager.java:39)
at org.gradle.api.internal.artifacts.ivyservice.resolveengine.DefaultDependencyResolver.resolve(DefaultDependencyResolver.java:82)
at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver$1.run(CacheLockingArtifactDependencyResolver.java:42)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:187)
at org.gradle.cache.internal.DefaultCacheAccess.useCache(DefaultCacheAccess.java:175)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.useCache(DefaultPersistentDirectoryStore.java:106)
at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.useCache(DefaultCacheFactory.java:193)
at org.gradle.api.internal.artifacts.ivyservice.DefaultCacheLockingManager.useCache(DefaultCacheLockingManager.java:65)
at org.gradle.api.internal.artifacts.ivyservice.CacheLockingArtifactDependencyResolver.resolve(CacheLockingArtifactDependencyResolver.java:40)
at org.gradle.api.internal.artifacts.ivyservice.SelfResolvingDependencyResolver.resolve(SelfResolvingDependencyResolver.java:45)
at org.gradle.api.internal.artifacts.ivyservice.ShortcircuitEmptyConfigsArtifactDependencyResolver.resolve(ShortcircuitEmptyConfigsArtifactDependencyResolver.java:55)
at org.gradle.api.internal.artifacts.ivyservice.ErrorHandlingArtifactDependencyResolver.resolve(ErrorHandlingArtifactDependencyResolver.java:47)
at org.gradle.api.internal.artifacts.ivyservice.DefaultConfigurationResolver.resolve(DefaultConfigurationResolver.java:46)
at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.resolveNow(DefaultConfiguration.java:240)
at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.getResolvedConfiguration(DefaultConfiguration.java:230)
at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated.getResolvedConfiguration(Unknown Source)
at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:463)
... 32 more
Caused by: org.gradle.api.internal.externalresource.transport.http.HttpRequestException: Could not GET 'http://repo.spring.io/libs-snapshot/org/springframework/boot/spring-boot-gradle-plugin/1.0.0.RC4/spring-boot-gradle-plugin-1.0.0.RC4.pom'.
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:80)
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.performRawGet(HttpClientHelper.java:66)
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.performGet(HttpClientHelper.java:70)
at org.gradle.api.internal.externalresource.transport.http.HttpResourceAccessor.getResource(HttpResourceAccessor.java:46)
at org.gradle.api.internal.externalresource.transport.http.HttpResourceAccessor.getResource(HttpResourceAccessor.java:32)
at org.gradle.api.internal.externalresource.transfer.ProgressLoggingExternalResourceAccessor.getResource(ProgressLoggingExternalResourceAccessor.java:38)
at org.gradle.api.internal.externalresource.transfer.DefaultCacheAwareExternalResourceAccessor.getResource(DefaultCacheAwareExternalResourceAccessor.java:60)
at org.gradle.api.internal.externalresource.transport.DefaultExternalResourceRepository.getResource(DefaultExternalResourceRepository.java:65)
at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$ArtifactResolver.getResource(ExternalResourceResolver.java:579)
at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$ArtifactResolver.findStaticResourceUsingPatterns(ExternalResourceResolver.java:564)
at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$ArtifactResolver.resolveMetaDataArtifact(ExternalResourceResolver.java:548)
at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.findMetaDataArtifact(ExternalResourceResolver.java:191)
at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:165)
at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.getDependency(MavenResolver.java:83)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CacheLockingModuleVersionRepository$2.run(CacheLockingModuleVersionRepository.java:54)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:237)
at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:308)
at org.gradle.cache.internal.DefaultPersistentDirectoryStore.longRunningOperation(DefaultPersistentDirectoryStore.java:114)
at org.gradle.cache.internal.DefaultCacheFactory$ReferenceTrackingCache.longRunningOperation(DefaultCacheFactory.java:185)
at org.gradle.api.internal.artifacts.ivyservice.DefaultCacheLockingManager.longRunningOperation(DefaultCacheLockingManager.java:57)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CacheLockingModuleVersionRepository.getDependency(CacheLockingModuleVersionRepository.java:52)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleVersionRepository.getDependency(CachingModuleVersionRepository.java:137)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache.CachedRepository.getDependency(CachedRepository.java:74)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver$RepositoryResolveState$RemoteModuleAccess.getDependency(RepositoryChainDependencyResolver.java:216)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver$StaticVersionRepositoryResolveState.process(RepositoryChainDependencyResolver.java:228)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver$RepositoryResolveState.resolve(RepositoryChainDependencyResolver.java:182)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.findLatestModule(RepositoryChainDependencyResolver.java:110)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.findLatestModule(RepositoryChainDependencyResolver.java:86)
at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainDependencyResolver.resolve(RepositoryChainDependencyResolver.java:61)
... 63 more
Caused by: org.apache.http.conn.HttpHostConnectException: Connection to http://repo.spring.io refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:190)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:294)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:640)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:479)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:137)
at org.apache.http.impl.client.DecompressingHttpClient.execute(DecompressingHttpClient.java:118)
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:111)
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.executeGetOrHead(HttpClientHelper.java:87)
at org.gradle.api.internal.externalresource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:78)
... 92 more
Caused by: java.net.ConnectException: Connection timed out: connect
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:127)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:180)
... 101 more
Below is the content of my Build.gradle file
buildscript {
repositories {
maven { url "http://repo.spring.io/libs-snapshot" }
mavenLocal()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.0.0.RC4")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'
repositories {
mavenCentral()
maven { url "http://repo.spring.io/libs-snapshot" }
}
dependencies {
compile("org.springframework.boot:spring-boot-starter-web")
compile("com.fasterxml.jackson.core:jackson-databind")
testCompile("junit:junit")
}
jar {
baseName = 'gs-rest-service'
version = '0.1.0'
}
task wrapper(type: Wrapper) {
gradleVersion = '1.11'
}
Please help me why the build is failing?? Is that anything to do with Proxy settings?
Ok, for me it works perfectly fine. If You have any proxy this is (was) a known issue. Have a look at setting up gradle's build environment.