Robolectric PowerMock java.lang.NoClassDefFoundError error while running a test - java

I want to integrate powermock to test firebase logic. I tried to run a test and got this:
java.lang.NoClassDefFoundError: org/mockito/cglib/proxy/MethodInterceptor
Here is my app.gradle:
testCompile 'junit:junit:4.12'
testCompile "org.powermock:powermock-module-junit4:1.7.0"
testCompile "org.powermock:powermock-module-junit4-rule:1.7.0"
testCompile "org.powermock:powermock-api-mockito:1.7.0"
testCompile "org.powermock:powermock-classloading-xstream:1.7.0"
testCompile "org.robolectric:robolectric:3.4.2"
testCompile 'org.mockito:mockito-core:2.1.0'
Here is my test:
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class)
#PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
#PrepareForTest({FirebaseAuth.class, FirebaseDatabase.class})
public class LoginTest {
#Before
public void setUp() {
PowerMockito.mockStatic(FirebaseAuth.class);
Mockito.when(FirebaseAuth.getInstance()).thenReturn(Mockito.mock(FirebaseAuth.class));
}
#Test
public void test() {
}
}

You are using 'org.mockito:mockito-core:2.1.0' with "org.powermock:powermock-api-mockito:1.7.0".
To use PowerMock with Mockito 2 the "org.powermock:powermock-api-mockito2:1.7.0" should be used.

You need the cglib library in your class path.
My solution is to always download a "complete" powermock ZIP from here. Those ZIP files contain everything you need in order to get going with PowerMock.

Related

Spock test case doesn't work without JUnit's #Test annotation

I have started new java 11, spring boot 2.3.1 project in IntelliJ.
I wanted to add spock to dependencies however I am facing a problem when trying to run example test case.
org.junit.runners.model.InvalidTestClassError: Invalid test class 'com.example.SpockSpec':
1. No runnable methods
This is list of my dependencies:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
testImplementation "org.codehaus.groovy:groovy-all:$groovyVersion"
testImplementation 'org.spockframework:spock-core:2.0-M2-groovy-3.0'
}
(groovy version is 3.0.0)
this is the spec:
class SpockSpec extends Specification {
def "result should be true"(){
given:
boolean a = false;
boolean b = true;
when:
boolean result = a || b;
then:
result == true;
}
}
Workaround is to add JUnit's #Test annotation before the method but I would prefer not to do that.
Also - when I do so testing only works when I run whole class.
How can I resolve the error?
Spock 1 is based on JUnit 4, but Spock 2 runs on the JUnit 5 platform, implementing its own engine (not JUnit Jupiter). So maybe you want to first read some documentation and then upgrade to JUnit 5 (not vintage). Right on top of the manual in chapter "getting started" there is a subchapter "Spock example project".

NoSuchMethodError: org.mockito.internal.runners.RunnerFactory.createStrict

I am using latest versions of JUnitParams, junit and mockito-all.
testCompile group: 'pl.pragmatists', name: 'JUnitParams', version: '1.1.1'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile group: 'org.mockito', name: 'mockito-all', version: '2.0.2-beta'
I keep getting NoSuchMethodError when running a JUnit test with annotation #RunWith(MockitoJUnitRunner.class).
java.lang.NoSuchMethodError: org.mockito.internal.runners.RunnerFactory.createStrict(Ljava/lang/Class;)Lorg/mockito/internal/runners/InternalRunner;
at org.mockito.junit.MockitoJUnitRunner.<init>(MockitoJUnitRunner.java:154)
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 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:49)
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)
What can be the problem that triggers NoSuchMethodError exception?
Code:
#RunWith(MockitoJUnitRunner.class)
public class MockTest {
#Mock
ServletUriComponentsBuilder servletUriComponentsBuilder;
#Before
public void setup() {
servletUriComponentsBuilder = mock(ServletUriComponentsBuilder.class);
}
#Test
public void shouldGenerateUrl() {
when(servletUriComponentsBuilder.fromUriString(anyString()).build().toString())
.thenReturn("test");
Assert.assertEquals("my message", "test", "test");
}
}
mockito-core
You have Mockito 1.x and 2.x on your classpath. I think that is because you have a dependency to mockito-all:2.0.2-beta and some of your other dependencies has a transitive dependency to mockito-core:1.x.
You should never use mockito-all with a build system that does your dependency management. Instead use
testCompile group: 'org.mockito', name: 'mockito-core', version: '2.0.2-beta'
or even a more current version (see The Central Repository)
Mockito documentation: https://github.com/mockito/mockito/wiki/Declaring-mockito-dependency
Please tell me, if this does not solve the problem.
Creation of mocks
This is not the cause of your problem but maybe helpful, too. You are creating the ServletUriComponentsBuilder twice. First the MockitoRunner creates it because of the #Mock annotation and then you override it with a new mock in you setup method. So either you do
#RunWith(MockitoJUnitRunner.class)
public class MockTest {
#Mock
ServletUriComponentsBuilder servletUriComponentsBuilder;
#Test
...
or you do
public class MockTest {
ServletUriComponentsBuilder servletUriComponentsBuilder;
#Before
public void setup() {
servletUriComponentsBuilder = mock(ServletUriComponentsBuilder.class);
}
#Test
...
You may even do this shorter
public class MockTest {
ServletUriComponentsBuilder servletUriComponentsBuilder
= mock(ServletUriComponentsBuilder.class);
#Test
...

"Unresolved reference:" errors with testCompile

Currently, I'm getting Unresolved reference: spek and Unresolved reference: test with testCompile / testRuntime:
project(":core") {
apply plugin: "kotlin"
dependencies {
// ... other dependencies
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlinVersion"
testCompile "org.jetbrains.spek:spek-api:$spekVersion"
testRuntime "org.jetbrains.spek:spek-junit-platform-engine:$spekVersion"
testCompile "com.nhaarman:mockito-kotlin:$mockitoVersion"
testCompile "com.natpryce:hamkrest:$hamkrestVersion"
}
}
However, when I switch them with compile / runtime, I can run the tests successfully!
Here's my spek test:
package com.mysampleapp
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertEquals
class DummySpec : Spek({
describe("a dummy") {
it("contains a number") {
val dummy = Dummy(1)
assertEquals(1, dummy.number)
}
}
})
Could someone please help me to debug this?
Thank you
I found out the cause. My tests are inside my Source Folder.
To fix this, I moved my tests out, so Source Folder will not overlap with Tests Source Folder.

ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory when trying to load InitialContext

I'm testing (with JUnit) an rest service and to make shure everything goes as intended i need to use some EJB methods. Say, i have:
the class under test, wich is of no interest here;
testing class
public class UploadServiceTest {
private final String RemoteBeanLookupKey = "/project/dao/TaskManager!ru.project.dao.TaskManager";
#EJB private TaskManager taskManager;
#Before
public void startEverythingNeeded() throws Exception {
InitialContext ctx = null;
Properties jndiProp = new Properties();
InputStream testConfStream = getClass().getClassLoader().getResourceAsStream("jndi.properties");
jndiProp.load(testConfStream);
ctx = new InitialContext(jndiProp);
taskManager = ((TaskManager) ctx.lookup(RemoteBeanLookupKey));
}
#Test
public void blablabla(){
}
}
jndi.properties
java.naming.factory.initial=org.jboss.naming.remote.client.InitialContextFactory
java.naming.provider.url=http-remoting://localhost:8080
remote.connection.default.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS=false
jboss.naming.client.ejb.context=true
remote.connection.default.username=admin
remote.connection.default.password=admin
gradle dependencies: testCompile group: 'org.wildfly', name: 'wildfly-ejb-client-bom', version: '8.2.0.Final', ext: 'pom', testCompile group: 'junit', name: 'junit', version: '4.11' and provided project(path: ':dao') (this is the module i want to get EJB from).
But when i try to run test, it fails with javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.remote.client.InitialContextFactory
[Root exception is java.lang.ClassNotFoundException: org.jboss.naming.remote.client.InitialContextFactory]
Other similar questions on here and on the net suggest to add jboss-client to CLASSPATH, but i've looked into README near jboss-client in my distribution and it sayed not to act like this and to make a gradle dependency instead. So I did.
Another strange thing about this: I got code and properties from tests to another module in same project (written by another coder). I tried to run those tests and they work as intended. I copied everything and even more (gradle depency), but get this exception.
I've tried to simplify the code in order to illustrate, I may have something important missing. If needed, I can copy some more parts of setup and code.
I changed the dependency on ejb-client from testCompile group: 'org.wildfly', name: 'wildfly-ejb-client-bom', version: '8.2.0.Final', ext: 'pom' to testCompile 'org.wildfly:wildfly-ejb-client-bom:10.0.0.Final' and it started working. Not sure if it is helpfull.

Firebase unit testing without involving a context

I am trying to unit test firebase code with JUnit 4 in Android Studio.
The following are the minimal unit test code and configs.
public class ATest {
private static Firebase f;
#BeforeClass
public static void init() {
f = new Firebase(FIREBASE_URL);
}
#Test
public void doTest(){}
}
build.gradle dependency
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.firebase:firebase-client-jvm:2.5.0'
}
However, when running unit testing, exception occur at the line inside init().
java.lang.RuntimeException: You need to set the Android context using Firebase.setAndroidContext() before using Firebase.
at com.firebase.client.core.Context.getPlatform(Context.java:45)
at com.firebase.client.core.Context.ensureLogger(Context.java:218)
at com.firebase.client.core.Context.initServices(Context.java:105)
at com.firebase.client.core.Context.freeze(Context.java:92)
at com.firebase.client.core.RepoManager.getLocalRepo(RepoManager.java:55)
at com.firebase.client.core.RepoManager.getRepo(RepoManager.java:19)
at com.firebase.client.Firebase.<init>(Firebase.java:172)
at com.firebase.client.Firebase.<init>(Firebase.java:177)
at com.firebase.client.Firebase.<init>(Firebase.java:155)
at mypackage.Test.init(Test.java:21)
I did a test with eclipse/maven, including firebase-client-jvm doesn't result in RuntimeException. What configuration am I missing to cause the jvm version of Firebase to require a Context?

Categories

Resources