I have been reading a lot about PowerMockito to mock static methods. So I have been trying to use v1 (not v2), although I don't really care which version of PowerMockito or testNG I use. I figure I missed some critical detail here in the configuration, but I am at a loss.
Using Oracle Java 1.8
subprojects.gradle:
testCompile group: 'org.testng', name: 'testng', version: '6.14.3'
testCompile group: 'org.powermock', name: 'powermock-module-testng', version: '1.7.4'
testCompile group: 'org.powermock', name: 'powermock-api-mockito', version: '1.7.4'
I checked my versioning of modules here
Test class
import org.mockito.*;
import org.mockito.invocation.*;
import org.mockito.stubbing.*;
import org.powermock.core.classloader.annotations.*;
import org.powermock.modules.testng.*;
import org.testng.*;
import org.testng.annotations.*;
import java.io.*;
import java.net.*;
import static org.powermock.api.mockito.PowerMockito.*;
#PrepareForTest({java.net.InetAddress.class})
public class testClass extends PowerMockTestCase {
#Test
public void exampleTest()
throws IOException, URISyntaxException, MyCustomException {
mockStatic(InetAddress.class);
// I use these three functions, so I think I have to mock them all?
when(InetAddress.getByName(Mockito.anyString()))
.thenReturn(InetAddresses.forString("111.0.0.111"));
when(InetAddress.getByAddress(Mockito.anyObject()))
.thenCallRealMethod();
when(InetAddress.getLocalHost()).thenCallRealMethod();
MyNewClass mnc = new MyNewClass();
mnc.someCodeUsingInetAddress();
}
This compiles and runs, but does not change the behavior of the function InetAddress.getByName() when called from someCodeUsingInetAddress().
Now I read here that I need to label the class with
#RunWith(PowerMockRunner.class). But IntelliJ won't let me import the PowerMockRunner.class from any of the possible sources, of which it is aware. Which also makes me wonder which one I should be trying to use.
org.testng.PowerMockRunner
org.testng.annotations.PowerMockRunner
org.powermock.modules.testng.PowerMockRunner
the list goes on...
Related
I'm trying to write a Java library that has a non-nullable API, and I'd like Kotlin to properly infer this non-nullability. I'm using JSR-305 annotations and its #TypeQualifierDefault to achieve the effect for the entire package, as per Kotlin's Java interop reference.
I build it all using Gradle 4.10.2 and I supply -Xjsr305=strict to the Kotlin compiler, as instructed. Yet, when I reflectively inspect the types from Kotlin, they are reported as platform types, e.g.:
fun sample.Foo.bar(T!): kotlin.collections.(Mutable)List<T!>!
What am I doing wrong that I don't get the following output?
fun sample.Foo.bar(T): kotlin.collections.(Mutable)List<T>
Note that Spring Framework 5 has a similar annotation named #NonNullApi.
I'm using OpenJDK 11.
PS. I know I can just annotate every method and parameter with #Nonnull, but I'm after global behavior and converting Kotlin's List<T!> to List<T>.
Here's the MCVE:
src/main/java/sampleAnnotation/NonNullPackage.java
package sampleAnnotation;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.*;
#Nonnull
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PACKAGE)
#TypeQualifierDefault({
ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE_USE
})
public #interface NonNullPackage {
}
src/main/java/foo/package-info.java
#NonNullPackage
package foo;
import sampleAnnotation.NonNullPackage;
src/main/java/foo/Foo.java
package foo;
import java.util.List;
public interface Foo {
<T> List<T> bar(T t);
}
src/main/kotlin/sampleKotlin/Main.kt
package sampleKotlin
import foo.Foo
import kotlin.reflect.full.memberFunctions
fun main(args : Array<String>) {
println(Foo::class.memberFunctions.first())
}
build.gradle
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.3.0'
}
wrapper {
gradleVersion = '4.10.2'
}
repositories {
mavenCentral()
}
dependencies {
compileOnly group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2'
compile group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib'
compile group: 'org.jetbrains.kotlin', name: 'kotlin-reflect'
}
compileKotlin {
kotlinOptions.freeCompilerArgs = ['-Xjsr305=strict']
}
tried to follow this and this but without any luck.
I am using Android studio 3.0 and junit 4.12. Windows 10.
What I have tried:
move the junit dependency up (tried test compilation and implementation scope)
delete the tests in Run - Edit configurations... - remove all under Android JUnit and Android App
My graddle looks like this:
apply plugin: 'kotlin'
dependencies {
implementation project(':domain')
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompileOnly 'junit:junit:4.12'
testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'io.reactivex.rxjava2:rxkotlin:2.1.0'
testImplementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testImplementation 'com.nhaarman:mockito-kotlin:1.1.0'
testImplementation 'org.amshove.kluent:kluent:1.14'
implementation 'com.google.api.client:google-api-client-repackaged-com-google-common-base:1.2.3-alpha'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
}
My test looks like this:
package ***.roompanel.data;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.TypeAdapterFactory;
import ***.roompanel.data.RestApi.ApiFieldNamingStrategy;
import ***.roompanel.data.RestApi.ApiGsonBuilder;
import ***.roompanel.data.RestApi.ApiItemTypeAdapterFactory;
import ***.roompanel.data.RestApi.ApiService;
import ***.roompanel.data.RestApi.IApiService;
import ***.roompanel.data.repository.EventRepository;
import ***.roompanel.domain.model.event.Event;
import ***.roompanel.domain.repository.IEventRepository;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertNotNull;
public class EventRepositoryTest {
IEventRepository repo;
#Before
public void setUp() {
TypeAdapterFactory typeAdatperFactory = new ApiItemTypeAdapterFactory(); // system to
FieldNamingStrategy fieldNamingStrategy = new ApiFieldNamingStrategy();
Gson gson = new ApiGsonBuilder(typeAdatperFactory, fieldNamingStrategy).build();
IApiService service = new ApiService(gson);
this.repo = new EventRepository(service);
}
#Test
public void events_void_success() throws Exception {
Date start = new Date(2017,10,01);
Date end = new Date(2017,10,12);
List<Event> events = (List<Event>) repo.load(start, end);
assertNotNull(events);
}
}
UPDATE:
./gradlew test
BUILD SUCCESSFUL in 25s
53 actionable tasks: 30 executed, 23 up-to-date
Stacktrace:
java.lang.RuntimeException: Stub!
at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
at junit.textui.TestRunner.<init>(TestRunner.java:54)
at junit.textui.TestRunner.<init>(TestRunner.java:48)
at junit.textui.TestRunner.<init>(TestRunner.java:41)
at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:224)
at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:207)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:61)
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.application.AppMainV2.main(AppMainV2.java:131)
This is not the solution, just a messy workaround (since it took too much time to solve it):
Uninstall and install the android studio 3.0 again. Do not update the
kotlin plugin and the android studio to newer versions.
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.
I am trying to add some Roboelectric unit tests to my app.
Using Roboelectric 3.0 i want to be able to test my activity PinActivity and the fragment that is in it.
import android.support.v7.app.AppCompatActivity;
import android.app.Fragment;
PinActivity extends AppCompatActivity {
gradle file contains:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.0"
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}
PinActivityTest contains: (Edited to add #Config did not fix)
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.*;
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class, sdk = 21)
public class PinActivityTest {
#Test
public void onCreate_shouldInflateLayout() throws Exception {
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
assertNotNull(activity);
}
Currently getting:
WARNING: No manifest file found at .\AndroidManifest.xml.Falling back to the Android OS resources only. To remove this warning, annotate your test class with #Config(manifest=Config.NONE). and java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
Why can't it find my AndroidManifest?
Anyone know how i can fix this or more Roboelectric tutorials with similar examples?
As log says, you forgot about #Config annotation, so it could not find your AndroidManifest file:
Try this:
#RunWith(RobolectricGradleTestRunner.class)
#Config(constants = BuildConfig.class, sdk = 21) public class PinActivityTest {
#Test
public void onCreate_shouldInflateLayout() throws Exception {
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get();
assertNotNull(activity);
}
As Roboelectric not support already API23, I set up test sdk as API 21.
EDIT: Change also:
PinActivity activity = Robolectric.buildActivity(PinActivity.class).create().get()
to
PinActivity activity = Robolectric.setupActivity(PinActivity.class);
NOTE: My Robolectric dependencies looks now:
testCompile("org.robolectric:robolectric:3.0") {
exclude module: 'classworlds'
exclude module: 'commons-logging'
exclude module: 'httpclient'
exclude module: 'maven-artifact'
exclude module: 'maven-artifact-manager'
exclude module: 'maven-error-diagnostics'
exclude module: 'maven-model'
exclude module: 'maven-project'
exclude module: 'maven-settings'
exclude module: 'plexus-container-default'
exclude module: 'plexus-interpolation'
exclude module: 'plexus-utils'
exclude module: 'wagon-file'
exclude module: 'wagon-http-lightweight'
exclude module: 'wagon-provider-api'
}
If you have any question, please free to ask.
Hope it help
Trying to build a hello world jersey test. https://jersey.java.net/documentation/2.5.1/test-framework.html makes it look so simple, but when overriding the configure method as documented doesn't work.
From the documentation
package api;
import static org.junit.Assert.assertEquals;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import org.junit.Test;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
public class JerseyTester extends JerseyTest {
#Path("hello")
public static class HelloResource {
#GET
public String getHello() {
return "Hello World!";
}
}
#Override
protected Application configure() {
return new ResourceConfig(HelloResource.class);
}
#Test
public void testHelloWorld() {
WebResource webResource = resource();
String responseMsg = webResource.path("helloworld").get(String.class);
assertEquals("Hello World", responseMsg);
}
}
The issue is the configure method override doesn't work - I get the error: "The return type is incompatible with JerseyTest.configure()". I also get the error: "Cannot instantiate the type ResourceConfig" - how can that be when the documentation explicitly says to instantiate it?!
This is so basic I don't know why it wouldn't work. I'm just trying to get a plain-jane jersey endpoint under test.
Here's my dependencies:
dependencies {
compile 'javax.ws.rs:jsr311-api:1.1.1'
compile 'com.sun.jersey:jersey-server:1.19'
compile 'com.sun.jersey:jersey-core:1.19'
compile 'com.sun.jersey:jersey-client:1.19'
compile 'com.sun.jersey:jersey-servlet:1.19'
compile 'com.sun.jersey:jersey-json:1.19'
compile 'com.yammer.metrics:metrics-core:2.2.0'
compile 'com.yammer.metrics:metrics-servlet:2.2.0'
compile 'com.yammer.metrics:metrics-jersey:2.2.0'
compile 'com.yammer.metrics:metrics-graphite:2.2.0'
compile 'log4j:log4j:1.2.16'
testCompile 'junit:junit-dep:4.10'
testCompile 'com.sun.jersey.jersey-test-framework:jersey-test-framework-grizzly2:1.19'
testCompile 'org.slf4j:slf4j-simple:1.6.1'
}
Yeah you're looking at the wrong documentation. The documentation you're looking at is for Jersey 2.x. But you are using Jersey 1.x. You could look at the documentation for 1.x, but there's not much going on there. Best thing to do is look at the source code tests for examples. You can also see another example at the bottom of this answer