Firebase admin sdk: IllegalArgumentException, Preconditions.checkArgument - java

I am getting the error below:
java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.json.webtoken.JsonWebSignature$Parser.parse(JsonWebSignature.java:599)
at com.google.firebase.auth.FirebaseToken.parse(FirebaseToken.java:44)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:456)
at com.google.firebase.auth.FirebaseAuth$4.execute(FirebaseAuth.java:449)
at com.google.firebase.internal.CallableOperation.call(CallableOperation.java:36)
at com.google.firebase.auth.FirebaseAuth.verifyIdToken(FirebaseAuth.java:413)
at d.d.pamper.test.ApplicationTest.testFire2(ApplicationTest.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
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)
I realize the stack is not very helpful. I've debugged inside the Admin SDK. It reads my service json correctly, the FirebaseAuth.getInstance() is not null, I can see my project id get set correctly.
This is how I'm initializing:
if(FirebaseApp.getApps().size() > 0) {
System.out.println("initialized already ");
return;
}
FirebaseOptions options = null;
try {
System.out.println("try initializing");
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(gservicesConfig.getInputStream()))
.setDatabaseUrl("https://pamperanywhere.firebaseio.com")
.build();
} catch (IOException e) {
e.printStackTrace();
}
FirebaseApp.initializeApp(options);
return;
This is how I'm testing my token:
#Test
public void testFire2() {
String idToken = "REFRESH TOKEN FROM FIREBASE";
if(!StringUtils.isEmpty(idToken)) {
FirebaseToken firebaseToken = null;
if(FirebaseAuth.getInstance() == null) {
System.out.println("FirebaseAuth.getInstance() == null");
}
try {
firebaseToken = FirebaseAuth.getInstance().verifyIdToken(idToken, true);
} catch (IllegalArgumentException e) {
System.out.println("exception+IllegalArgumentException");
e.printStackTrace();
} catch (FirebaseAuthException e) {
System.out.println("exception+FirebaseAuthException");
e.printStackTrace();
}
if (firebaseToken == null) {
System.out.println("firebaseToken == null");
}
}
}
I'm not sure why its throwing IllegalArgumentException. I'm able to login to the application fine (front end), I see my refresh token (front end) but on the Admin side its giving me this issue. I am sure I'm passing the correct token because I can login and see the token (front end).
Maven is:
<dependency>
<groupId>com.google.firebase</groupId>
<artifactId>firebase-admin</artifactId>
<version>6.2.0</version>
</dependency>
Thank you for your help.

An ID token should be a valid JWT with 3 segments (separated by dots). Refresh tokens are certainly not that. Therefore the underlying token parser is failing with the above assertion error. Here's the relevant bit of code from the Google API client. Basically it cannot find any dots in the given token string.
public JsonWebSignature parse(String tokenString) throws IOException {
// split on the dots
int firstDot = tokenString.indexOf('.');
Preconditions.checkArgument(firstDot != -1);
...

There's a listener:
firebase.auth().onIdTokenChanged((user: firebase.User) => {
console.log("onIdTokenChanged");
if(user && user.uid) {
user.getIdToken(false)
.then((data: any) => {
console.log("data: ", data);
this.idToken = data;
});
}
});
this gets invoked every one hour. I thought I had to implement this logic myself!
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#onIdTokenChanged
From official; above is from Ionic2/Angular2, I have that in a dataServiceProvider 's constructor.
firebase.auth().onIdTokenChanged(function(user) {
if (user) {
// User is signed in or token was refreshed.
}
});

Related

[ERROR]TransactionBuilder. - The transaction currently built is missing an attachment for :classnet/corda/core/contracts/CommandData

When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.When trying to run test for CORDA the given Test case getting the following error. I am using JDK 1.8. Intellij IDEA.
MetalContract
import com.template.states.MetalState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.CommandData;
import net.corda.core.contracts.Contract;
import net.corda.core.contracts.ContractState;
import net.corda.core.identity.Party;
import net.corda.core.transactions.LedgerTransaction;
import org.jetbrains.annotations.NotNull;
import java.security.PublicKey;
import java.util.List;
// ************
// * Contract *
// ************
public class MetalContract implements Contract {
// This is used to identify our contract when building a transaction.
public static final String CID = "com.template.contracts.MetalContract";
// A transaction is valid if the verify() function of the contract of all the transaction's input and output states
// does not throw an exception.
#Override
public void verify(#NotNull LedgerTransaction tx) throws IllegalArgumentException{
if (tx.getCommands().size() != 1)
throw new IllegalArgumentException("Transaction must have one Command.");
Command command = tx.getCommand(0);
CommandData commandType = command.getValue();
List<PublicKey> requiredSigners = command.getSigners();
// -------------------------------- Issue Command Contract Rules ------------------------------------------
if (commandType instanceof Issue) {
// Issue transaction logic
// Shape Rules
if (tx.getInputs().size() != 0)
throw new IllegalArgumentException("Issue cannot have inputs");
if (tx.getOutputs().size() != 1)
throw new IllegalArgumentException("Issue can only have one output");
// Content Rules
ContractState outputState = tx.getOutput(0);
if (!(outputState instanceof MetalState))
throw new IllegalArgumentException("Output must be a metal State");
MetalState metalState = (MetalState) outputState;
if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
throw new IllegalArgumentException("Metal is not Gold or Silver");
}
// Signer Rules
Party issuer = metalState.getIssuer();
PublicKey issuersKey = issuer.getOwningKey();
if (!(requiredSigners.contains(issuersKey)))
throw new IllegalArgumentException("Issuer has to sign the issuance");
}
// -------------------------------- Transfer Command Contract Rules ------------------------------------------
else if (commandType instanceof Transfer) {
// Transfer transaction logic
// Shape Rules
if (tx.getInputs().size() != 1)
throw new IllegalArgumentException("Transfer needs to have one input");
if (tx.getOutputs().size() != 1)
throw new IllegalArgumentException("Transfer can only have one output");
// Content Rules
ContractState inputState = tx.getInput(0);
ContractState outputState = tx.getOutput(0);
if (!(outputState instanceof MetalState))
throw new IllegalArgumentException("Output must be a metal State");
MetalState metalState = (MetalState) inputState;
if (!metalState.getMetalName().equals("Gold")&&!metalState.getMetalName().equals("Silver")){
throw new IllegalArgumentException("Metal is not Gold or Silver");
}
// Signer Rules
Party owner = metalState.getOwner();
PublicKey ownersKey = owner.getOwningKey();
if (!(requiredSigners.contains(ownersKey)))
throw new IllegalArgumentException("Owner has to sign the transfer");
}
else throw new IllegalArgumentException("Unrecognised command.");
}
// Used to indicate the transaction's intent.
public static class Issue implements CommandData {}
public static class Transfer implements CommandData {}
}
package com.template.contracts;
import com.template.states.MetalState;
import com.template.contracts.MetalContract;
import net.corda.core.contracts.Contract;
import net.corda.core.identity.CordaX500Name;
import net.corda.testing.contracts.DummyState;
import net.corda.testing.core.DummyCommandData;
import net.corda.testing.core.TestIdentity;
import net.corda.testing.node.MockServices;
import org.junit.Test;
import static net.corda.testing.node.NodeTestUtils.transaction;
public class ContractTests {
private final TestIdentity Mint = new TestIdentity (new CordaX500Name ("mint", "", "GB"));
private final TestIdentity TraderA = new TestIdentity (new CordaX500Name ("traderA", "", "GB"));
private final TestIdentity TraderB = new TestIdentity (new CordaX500Name ("traderB", "", "GB"));
private final MockServices ledgerServices = new MockServices();
private MetalState metalState = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
private MetalState metalStateInput = new MetalState("Gold", 10, Mint.getParty(), TraderA.getParty());
private MetalState metalStateOutput = new MetalState("Gold", 10, Mint.getParty(), TraderB.getParty());
#Test
public void metalContractImplementsContract() {
assert (new MetalContract() instanceof Contract);
}
#Test
public void MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction() {
transaction(ledgerServices, tx -> {
// Issuer is not a required signer, will fail
tx.output(MetalContract.CID, metalState);
tx.command(TraderA.getPublicKey(), new MetalContract.Issue());
tx.fails();
return null;
});
transaction(ledgerServices, tx -> {
// Issuer is a required, will verify
tx.output(MetalContract.CID, metalState);
tx.command(Mint.getPublicKey(), new MetalContract.Issue());
tx.verifies();
return null;
});
}
}
The Error is as following .
[ERROR] 12:35:10,086 [main] transactions.TransactionBuilder. - The transaction currently built is missing an attachment for class: net/corda/core/contracts/CommandData.
Attempted to find a suitable attachment but could not find any in the storage.
Please contact the developer of the CorDapp for further instructions.
java.lang.NoClassDefFoundError: net/corda/core/contracts/CommandData
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:468)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:405)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at net.corda.serialization.internal.model.TypeIdentifier$Unparameterised.getLocalType(TypeIdentifier.kt:151)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:38)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1$1.apply(TypeLoader.kt:25)
at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:38)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader$load$noCarpentryRequired$1.invoke(TypeLoader.kt:25)
at kotlin.sequences.TransformingSequence$iterator$1.next(Sequences.kt:149)
at kotlin.sequences.FilteringSequence$iterator$1.calcNext(Sequences.kt:109)
at kotlin.sequences.FilteringSequence$iterator$1.hasNext(Sequences.kt:133)
at kotlin.collections.MapsKt__MapsKt.putAll(Maps.kt:339)
at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:504)
at kotlin.collections.MapsKt__MapsKt.toMap(Maps.kt:498)
at net.corda.serialization.internal.model.ClassCarpentingTypeLoader.load(TypeLoader.kt:45)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.reflect(RemoteSerializerFactory.kt:129)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.access$reflect(RemoteSerializerFactory.kt:47)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:71)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory$get$1.invoke(RemoteSerializerFactory.kt:47)
at net.corda.serialization.internal.amqp.DefaultDescriptorBasedSerializerRegistry.getOrBuild(DescriptorBasedSerializerRegistry.kt:28)
at net.corda.serialization.internal.amqp.DefaultRemoteSerializerFactory.get(RemoteSerializerFactory.kt:66)
at net.corda.serialization.internal.amqp.ComposedSerializerFactory.get(SerializerFactory.kt)
at net.corda.serialization.internal.amqp.DeserializationInput.readObject(DeserializationInput.kt:172)
at net.corda.serialization.internal.amqp.DeserializationInput.readObjectOrNull(DeserializationInput.kt:147)
at net.corda.serialization.internal.amqp.DeserializationInput$deserialize$1.invoke(DeserializationInput.kt:124)
at net.corda.serialization.internal.amqp.DeserializationInput.des(DeserializationInput.kt:99)
at net.corda.serialization.internal.amqp.DeserializationInput.deserialize(DeserializationInput.kt:119)
at net.corda.serialization.internal.amqp.AbstractAMQPSerializationScheme.deserialize(AMQPSerializationScheme.kt:145)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1$1.invoke(SerializationScheme.kt:105)
at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:105)
at net.corda.serialization.internal.SerializationFactoryImpl$deserialize$1.invoke(SerializationScheme.kt:73)
at net.corda.core.serialization.SerializationFactory.asCurrent(SerializationAPI.kt:85)
at net.corda.serialization.internal.SerializationFactoryImpl.deserialize(SerializationScheme.kt:105)
at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt:78)
at net.corda.core.internal.TransactionUtilsKt$deserialiseComponentGroup$1.invoke(TransactionUtils.kt)
at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
at net.corda.core.internal.LazyMappedList.get(InternalUtils.kt:567)
at java.util.AbstractList$Itr.next(AbstractList.java:358)
at net.corda.core.transactions.LedgerTransaction.createLtxForVerification(LedgerTransaction.kt:668)
at net.corda.core.transactions.LedgerTransaction.access$createLtxForVerification(LedgerTransaction.kt:44)
at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:154)
at net.corda.core.transactions.LedgerTransaction$internalPrepareVerify$1.invoke(LedgerTransaction.kt:44)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder$withAttachmentsClassloaderContext$1.invoke(AttachmentsClassLoader.kt:345)
at net.corda.core.serialization.SerializationFactory.withCurrentContext(SerializationAPI.kt:71)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext(AttachmentsClassLoader.kt:344)
at net.corda.core.serialization.internal.AttachmentsClassLoaderBuilder.withAttachmentsClassloaderContext$default(AttachmentsClassLoader.kt:319)
at net.corda.core.transactions.LedgerTransaction.internalPrepareVerify$core(LedgerTransaction.kt:146)
at net.corda.core.transactions.LedgerTransaction.verify(LedgerTransaction.kt:136)
at net.corda.core.transactions.TransactionBuilder.addMissingDependency(TransactionBuilder.kt:185)
at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core(TransactionBuilder.kt:165)
at net.corda.core.transactions.TransactionBuilder.toWireTransactionWithContext$core$default(TransactionBuilder.kt:133)
at net.corda.core.transactions.TransactionBuilder.toWireTransaction(TransactionBuilder.kt:130)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.toWireTransaction$test_utils(TestDSL.kt:131)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.verifies(TestDSL.kt:175)
at net.corda.testing.dsl.Verifies$DefaultImpls.failsWith(LedgerDSLInterpreter.kt:45)
at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.failsWith(TransactionDSLInterpreter.kt)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.failsWith(TestDSL.kt:74)
at net.corda.testing.dsl.Verifies$DefaultImpls.fails(LedgerDSLInterpreter.kt:75)
at net.corda.testing.dsl.TransactionDSLInterpreter$DefaultImpls.fails(TransactionDSLInterpreter.kt)
at net.corda.testing.dsl.TestTransactionDSLInterpreter.fails(TestDSL.kt:74)
at net.corda.testing.dsl.TransactionDSL.fails(TransactionDSLInterpreter.kt)
at com.template.contracts.ContractTests.lambda$MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction$8(ContractTests.java:134)
at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt:54)
at net.corda.testing.node.NodeTestUtils$transaction$1.invoke(NodeTestUtils.kt)
at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt:39)
at net.corda.testing.node.NodeTestUtils$ledger$2.invoke(NodeTestUtils.kt)
at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt:231)
at net.corda.testing.internal.InternalTestUtilsKt$withTestSerializationEnvIfNotSet$1.invoke(InternalTestUtils.kt)
at net.corda.testing.common.internal.CommonSerializationTestHelpersKt.asContextEnv(CommonSerializationTestHelpers.kt:11)
at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv(InternalSerializationTestHelpers.kt:33)
at net.corda.testing.internal.InternalSerializationTestHelpersKt.asTestContextEnv$default(InternalSerializationTestHelpers.kt:31)
at net.corda.testing.internal.InternalTestUtilsKt.withTestSerializationEnvIfNotSet(InternalTestUtils.kt:231)
at net.corda.testing.node.NodeTestUtils.ledger(NodeTestUtils.kt:36)
at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt:53)
at net.corda.testing.node.NodeTestUtils.transaction$default(NodeTestUtils.kt:51)
at net.corda.testing.node.NodeTestUtils.transaction(NodeTestUtils.kt)
at com.template.contracts.ContractTests.MetalContractRequiresTheIssuerToBeARequiredSignerInTheTransaction(ContractTests.java:130)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.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.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:64)
Caused by: java.lang.ClassNotFoundException: net.corda.core.contracts.CommandData
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at net.corda.core.serialization.internal.AttachmentsClassLoader.loadClass(AttachmentsClassLoader.kt:289)
... 115 more
build.gradle from Contract module
apply plugin: 'net.corda.plugins.cordapp'
apply plugin: 'net.corda.plugins.cordformation'
cordapp {
targetPlatformVersion corda_platform_version
minimumPlatformVersion corda_platform_version
contract {
name "Template CorDapp"
vendor "Corda Open Source"
licence "Apache License, Version 2.0"
versionId 1
}
}
sourceSets {
main{
java {
srcDir 'src/main/java'
java.outputDir = file('bin/main')
}
}
test{
java{
srcDir 'src/test/java'
java.outputDir = file('bin/test')
}
}
}
dependencies {
// Corda dependencies.
cordaCompile "$corda_release_group:corda-core:$corda_release_version"
cordaRuntime "$corda_release_group:corda:$corda_release_version"
testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
}
It looks like something wrong with your project structure since it is a NoClassDefFoundError of a core package.
Try closing the project and also removing the project from your recent project list.
And open the project folder then follow the prompt to import Gradle project.
Edit Configurations and choose "JAR manifest" for "Shorten command line":

How to resolve this NullPointerException being thrown from HibernateTemplate's find(String query) method

How do I resolve this NullPointerException ?
A little background , I am developing a Spring based Project and using HibernateTemlate in DAO layer to do all database related operations.
here is the snippet of code which i have extracted out of my test class which is throwing NullPointerException.
try {
List<Object[]> list = (List<Object[]>) ht.find("select uomId,uomModel from in.nit.model.Uom");
System.out.println(list);
}catch(NullPointerException e) {
e.printStackTrace();
}
And this is the stacktrace of the exception on the console.
```
java.lang.NullPointerException
at in.nit.dao.impl.UomDaoImplTest.test(UomDaoImplTest.java:28)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
```
Here is my model class
```
#Entity
#Table(name="uomtab")
public class Uom {
#Id #GeneratedValue #Column(name="umid") private Integer uomId;
#Column(name="utype") private String uomType;
#Column(name="umodel") private String uomModel;
#Column(name="udesc") private String uomDesc;
public Uom() {
super();
}
public Uom(Integer uomId) {
this.uomId = uomId;
}
public Integer getUomId() {
return uomId;
}
public void setUomId(Integer uomId) {
this.uomId = uomId;
}
public String getUomType() {
return uomType;
}
public void setUomType(String uomType) {
this.uomType = uomType;
}
public String getUomModel() {
return uomModel;
}
public void setUomModel(String uomModel) {
this.uomModel = uomModel;
}
public String getUomDesc() {
return uomDesc;
}
public void setUomDesc(String uomDesc) {
this.uomDesc = uomDesc;
}
#Override
public String toString() {
return "Uom [uomId=" + uomId + ", uomType=" + uomType + ", uomModel=" + uomModel + ",
uomDesc=" + uomDesc + "]";
}
}
```
Also even though the find(String Query) method is deprecated,I have extensively used it in other dao classes of my project which works smooth and fine.
What could be the possible reasons for this exception blowing up my code?
You shouldn't catch that NullPointerException
What is line 28 in your code?
Did you try and debug the line? If it is the ht.find line, the only thing that makes sense is that your HibernateTemplate is null and has not been set correctly.
your error is in class "UomDaoImplTest". That has no relation with Hibernate Template.
can you post your test class.

Can not Create a Mock call for Method for Junit

Hi So I'm new to Junit and Mockito, so please bare with some misconception/mistakes that Ive made. I have a springbott service that I wanted to test and I want to mock a method call that is being made in one of the methods that I am testing but It will not work for some reason. I used both when(xxx.method(anyArgs)).return(someData) as well as doReturn(someData).when(xxx).method(anyArgs); But I still get the same type of error: InvalidUseOfMatchersException. I mock the service layer but I can not figure out what causes the issue.
The Exact Stack Trace:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
My Service Layer Code:
// imports here
#Service
#AllArgsConstructor
public class EventServiceImpl implements EventService {
private EventModelRepo eventModelRepo;
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
// methods that dont matter
public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}
public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();
InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}
public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}
And here is my Junit:
//imports
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");
//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}
So turns out one of the commentors on my post was correct. You can not mock a call from a #InjectMocks. But if you want to you need to have another annotation added to it. That annotation being #Spy. This annotation should be added in the test class, above the #InjectMocks.
More can be found here
#RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {
#Mock
private EventModelRepo eventModelRepo;
#Spy
#InjectMocks
private EventServiceImpl eventServiceImpl ;
#Test
public void validatePostDataTest() {
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);
}
}

Why does dom4j throw InvalidXPathException for a valid XPath only in my test environment?

I'm working on authoring some unit testing for some code that I've got working in a system, but I'm having problems with InvalidXPathException's being thrown on valid XPaths.
Using //external|//inline to extract out certain elements out of a DOM4J document, and it works in production but not in my test environment. There shouldn't be an issue as it's a valid XPath that I've tested outside of the environment.
Any help would be appreciated!
jUnit/Easymock test:
#Test
public void testgetDCR_success(){
RequestContext context = EasyMock.createMock(RequestContext.class);
FileDal dal = EasyMock.createMock(FileDal.class);
String xmlContent = "<xml>your sample stuff</xml>";
Document sampleDoc = Dom4jUtils.newDocument(xmlContent);
InputStream stream = null;
try {
stream = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
} catch(IOException e) {
Assert.fail("Could not open file stream for test.");
}
EasyMock.expect(context.getFileDal()).andReturn(dal).anyTimes();
EasyMock.expect(dal.getRoot()).andReturn("").anyTimes();
EasyMock.expect(dal.getSeparator()).andReturn('/').anyTimes();
EasyMock.expect(dal.exists("/some/path")).andReturn(true);
EasyMock.expect(dal.read("/some/path")).andReturn(xmlContent);
EasyMock.expect(dal.getStream("some/path")).andReturn(stream);
EasyMock.replay(context);
EasyMock.replay(dal);
Document doc = new DefaultTransformationService().getDCR(context, "some/path");
Assert.assertEquals(sampleDoc, doc);
}
Lead up to the issue:
#Override
public Document getDCR(RequestContext context, String relativePath) {
LOGGER.debug(">> getDCR");
if (StringUtils.isBlank(relativePath)) {
LOGGER.error("No origin file path given");
LOGGER.debug("<< getDCR");
return null;
}
Document dcrDoc = null;
try {
dcrDoc = ExternalUtils.readXmlFile(context, relativePath);
}catch (RuntimeException e){
LOGGER.error("No DCR found at file path: "+relativePath,e);
LOGGER.debug("<< getDCR");
return null;
}
if (dcrDoc == null) {
LOGGER.error("Unable to open xml file: " + relativePath);
LOGGER.debug("<< getDCR");
return null;
}
LOGGER.debug("<< getDCR");
Set<String> parsedPaths = new HashSet<String>();
parsedPaths.add(relativePath);
return parseData(context, dcrDoc, parsedPaths);
}
private Document parseData(RequestContext context, Document dcr, Set<String> parsedPaths) {
LOGGER.debug(">> parseData");
// get all nodes that would be converted.
#SuppressWarnings("unchecked")
List<Element> elements = dcr.selectNodes("//external|//inline");
// For each of the nodes present within the document that are of type external or inline
for (Element element : elements) {
// process each element in the list of selected elements.
processElement(context, element, parsedPaths);
}
LOGGER.debug("<< parseData");
return dcr;
}
Stack trace:
org.dom4j.InvalidXPathException: Invalid XPath expression: '//external|//inline'. Caused by: org/jaxen/dom4j/Dom4jXPath
at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:362)
at org.dom4j.xpath.DefaultXPath.<init>(DefaultXPath.java:59)
at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
at org.dom4j.tree.AbstractNode.selectNodes(AbstractNode.java:164)
at com.sample.project.service.impl.DefaultTransformationService.parseData(DefaultTransformationService.java:163)
at com.sample.project.service.impl.DefaultTransformationService.getDCR(DefaultTransformationService.java:144)
at com.sample.project.service.impl.DefaultTransformationServiceTest.testgetDCR_success(DefaultTransformationServiceTest.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Looking at the DOM4J source code, one can see that the root cause for that exception is not necessarily an invalid XPath expression:
protected static XPath parse(String text) {
try {
return new Dom4jXPath(text);
} catch (JaxenException e) {
throw new InvalidXPathException(text, e.getMessage());
} catch (Throwable t) {
throw new InvalidXPathException(text, t);
}
}
And given how the message looks, one can conclude that Throwable was catched. From InvalidXPathException:
public InvalidXPathException(String xpath, Throwable t) {
super("Invalid XPath expression: '" + xpath
+ "'. Caused by: " + t.getMessage());
}
Unfortunately, DOM4J hides the original exception in this case, but
Caused by: org/jaxen/dom4j/Dom4jXPath
implies that the original exception is a NoClassDefFoundError.
However, it is strange that that Dom4jXPath cannot be found while JaxenException is obviously found (since they live in the same jar (jaxen)). Anyway, it looks like your classpath is not set up properly.
BTW, the preceding "analysis" is based on DOM4J 1.6.1., so if you use another version YMMV.

Use Robolectric to test Activity with Loader

I have an Activity with a Spinner that uses a Loader to fetch data from the ContentProvider (as advised in several sources and as I've done before):
protected void onCreate(Bundle savedInstanceState) {
// ...
account = (Spinner) findViewById(R.id.account);
account.setAdapter(
new SimpleCursorAdapter(
this,
android.R.layout.simple_spinner_item,
null,
new String[]{ Contract.Accounts.COL_NAME },
new int[]{ android.R.id.text1 },
0));
getLoaderManager().initLoader(LOADER_ID_ACCOUNT, null, this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this,
Contract.Accounts.CONTENT_URI,
null,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
((SimpleCursorAdapter)account.getAdapter()).swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
((SimpleCursorAdapter)account.getAdapter()).swapCursor(null);
}
So far so good, the app works like a charm when I run it, but the unit tests I had for this Activity won't run now.
#Test
public void testAllElementsExist() {
Activity activity = setupActivity(AddTransactionActivity.class);
assertTrue(activity.findViewById(R.id.category) != null);
assertTrue(activity.findViewById(R.id.created_on_date) != null);
assertTrue(activity.findViewById(R.id.created_on_time) != null);
assertTrue(activity.findViewById(R.id.account) != null);
assertTrue(activity.findViewById(R.id.description) != null);
}
Even the most basic test fails:
java.lang.NullPointerException
at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:328)
at android.widget.SimpleCursorAdapter.swapCursor(SimpleCursorAdapter.java:345)
at pt.lemonade.AddTransactionActivity.onLoadFinished(AddTransactionActivity.java:185)
at pt.lemonade.AddTransactionActivity.onLoadFinished(AddTransactionActivity.java:28)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:482)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:450)
at android.content.Loader.deliverResult(Loader.java:143)
at android.content.CursorLoader.deliverResult(CursorLoader.java:113)
at android.content.CursorLoader.deliverResult(CursorLoader.java:43)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:254)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:91)
at android.os.ShadowAsyncTaskBridge.onPostExecute(ShadowAsyncTaskBridge.java:22)
at org.robolectric.shadows.ShadowAsyncTask$1$1.run(ShadowAsyncTask.java:40)
at org.robolectric.util.Scheduler$PostedRunnable.run(Scheduler.java:182)
at org.robolectric.util.Scheduler.runOneTask(Scheduler.java:125)
at org.robolectric.util.Scheduler.advanceTo(Scheduler.java:110)
at org.robolectric.util.Scheduler.advanceToLastPostedRunnable(Scheduler.java:86)
at org.robolectric.util.Scheduler.unPause(Scheduler.java:26)
at org.robolectric.shadows.ShadowLooper.unPause(ShadowLooper.java:231)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:270)
at org.robolectric.util.ActivityController.visible(ActivityController.java:166)
at org.robolectric.util.ActivityController.setup(ActivityController.java:202)
at org.robolectric.Robolectric.setupActivity(Robolectric.java:1388)
at pt.lemonade.AddTransactionActivityTest.testAllElementsExist(AddTransactionActivityTest.java:65)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:236)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Is this a known issue of Robolectric 2.4? Is there a workaround that doesn't translate into writing a bunch of shadow classes?
Tools of trade: Android Studio 1.1.0 with Unit Testing experimental feature activated, Gradle plugin 1.0.1, Robolectric 2.4
Also, some aside questions: I've recently heard that it's best to use RxJava Observables because it's easier to test. Can it be used as a substitute to the LoaderManager? How can I cache the results as the LoaderManager does? Can you give me a working example of a query to the ContentProvider and a unit test so I can evaluate?
In case anyone falls into the same issue: Robolectric lacked ShadowSimpleCursorAdapter#swapCursor implementation. I've added that method along with other modifications and created a pull request. You may find it in the master branch. As for anyone still using version 2.4, check this out: https://github.com/robolectric/robolectric/issues/1677

Categories