I am using mockito for my unit tests. Consider the following snippet
ThirdPartyClass tpo = mock(ThirdPartyClass.class);
doNothing().when(tpo).someMethod();
ThirdPartyClass is from a third party jar, lets say tp.jar. Now tp.jar is not an uber jar. Here is what ThirdPartyClass looks like
class ThirdPartyClass
{
SomeOtherClass memberObject;
public ThirdPartyClass(){}
/*Rest of the code*/
}
Now, when i try to run my unit tests, i get java.lang.ClassNotFoundException for SomeOtherClass. Remember that tp.jar is not an uber jar so it makes sense that SomeOtherClass is not in my classpath.
But why is mockito not able to handle this transitive dependency? Is there any way to ignore all transitive dependencies?
"Only mock types that you own" is the way to go here.
One reason for that is exactly what you describe: the test set up becomes too complicated, e.g. because of dependencies.
So instead of mocking the ThirdPartyClass, you create some sort of Adapter and then mock that class.
interface ThirdPartyAdapter {
void someMethod(); // only put method here that you really use
}
And then mock that thing instead:
ThirdPartyAdapter tpo = mock(ThirdPartyAdapter.class);
doNothing().when(tpo).someMethod();
And in production, delegate to the ThirdPartyClass:
class UsefulThing implements ThirdPartyAdapter {
ThirdPartyClass wrapped;
UsefulThing(ThirdPartyClass wrapped) {
this.wrapped = wrapped;
}
#Override
void someMethod() {
wrapped.someMethod()
}
}
Benefits:
Tests and production code is more robust to changes of the third party classes
You can use your own domain terms for methods instead of what the third party dictates
The relationship between your code and the third party code becomes clearer (and is only visible at a single place in your code)
I highly recommend Growing Object Oriented Software by Freeman & Pryce - or check the mockito docks for a quick start.
Mockito works by creating a subclass of the class to be mocked. So the class to be mocked has to compile. Could perhaps be solved by adding the jar that contains SomeOtherClass to your dependency management with scope test.
If you are going to mock ThirdPartyClass then SomeOtherClass MUST be on your compile-time and runtime classpath. Without seeing how you are building/running it's difficult to give real help
You need to ensure that all the required classes (jars) are on
The compile classpath
The runtime classpath
If you are using a build tool like Gradle or Maven to build & run then the classpaths, including transitive dependencies, will be managed for you. If you are compiling/running by hand you will need to ensure that the transitive dependencies are on the compile-time & runtime classpaths.
Related
I need to add an annotation to a class which is in a sperate dependency (in a separate jar) of the project that I am working on. I am wondering that can I do this in Java?
As an example, I need to add an annotation HisClass without touching the source code of HisClass.
public class HisClass{
// ...
}
So, that the above class should be look like below at the build time,
#MyAnnot ( me = MyClass.class )
public class HisClass{
// ...
}
There are many ways:
Write a compiler plugin for javac, and make it add the annotations. This will be quite difficult, as the plugin API has nearly no documentation.
2.(Maybe not possible) Inject the annotation after compiling. Add an extra buildstep after compiling and use a library like ASM to add this annotation to the classfile.
I have an application I want to test:
import foo.ExtClass;
public class App {
public static void main(String[] args) {
ExtClass ext = new ExtClass();
...
}
}
I want to write a unit test for this application, however I do not want to use the foo.ExtClass, but use another mock implementation for the class.
Normally I would use a factory to instantiate the class according to some configuration that can be controlled in the unit test.
However, in this case, I cannot modify the tested app.
I was thinking in the direction of writing a custom class loader to load the mock class instead of the real class - not sure if this is possible without any modification to the tested app, and how.
As an option you can use custom classloader, which will substite your class with a testing one. So basically instead of loading ExtClass from your app package, your classloader will load the same class from your testing package with the mock implementation.
Here is an example:
How to replace classes in a running application in java ?
Also there is very usefull tutorial: https://zeroturnaround.com/rebellabs/reloading-objects-classes-classloaders/
The approach I finally used:
Created a separate project with my mock implementation of foo.ExtClass,
and the unit tests.
This way the mock implementation appeared in the classpath before the real implementation, and the original (tested) project remained untouched.
Hi I need to write Junit tests for an Android project but it has JNI methods as it uses webkit.Is there any way I can test those android methods(I dont want to test JNI methods).
Its like:
public void androidMethod(){
//some android code
nativeInit(); //how do I mock such methods?
//some code again
}
I have tried powermock,easymock,roboelectric but wasnt successful.Please help me.
I yesterday found I could solve this with Mockito (I didn't try powermock or easymock). Assuming your class is class C, my solution is:
C c=spy(new C);
doNothing().when(c).nativeInit();
c.androidMethod()
verify(c).nativeInit();
This does, of course, require that nativeInit is visible to the test.
Similar Problem
I had the same problem event though I was already using mockito in JUnit tests under src/test. Once I added tests under src/androidTest I started having issues, including this crash:
Mockito cannot mock/spy because :
- final class
And after making the class open, manually, I still got crashes in the JNI layer as it tried to load the *.so library (which wouldn't happen if mocks were working properly).
Working Solution
Instead, what I had to do was open the class for testing purposes using Kotlin's all-open plugin. The process is also explained well in this recent medium post but it boils down to the following four simple changes that are also modeled in one of the architecture components sample apps:
1. Make these additions to build.gradle:
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-allopen:${versions.kotlin}"
}
}
apply plugin: "kotlin-allopen"
allOpen {
// marker for classes that we want to be able to extend in debug builds
annotation 'com.your.package.name.OpenClass'
}
2. Add the corresponding annotations in the debug flavor. For example: app/src/debug/java/com/your/package/name/OpenForTesting.kt
package com.your.package.name
#Target(AnnotationTarget.ANNOTATION_CLASS)
annotation class OpenClass
#OpenClass
#Target(AnnotationTarget.CLASS)
annotation class OpenForTesting
3. Add the corresponding annotation in the release flavor. For example: app/src/release/java/com/your/package/name/OpenForTesting.kt
package com.your.package.name
#Target(AnnotationTarget.CLASS)
annotation class OpenForTesting
4. Add the #OpenForTesting annotation to the class that needs to be mocked
package com.your.package.name
#OpenForTesting
class JniClassOfVictory {
...
external fun nativeInit()
...
companion object {
init {
System.loadLibrary("victoryeveryday")
}
}
}
The result is a flexible way to mark classes as open without actually making them open in release builds. Of course, this is because the #OpenForTesting annotation that we created in release is not marked with #OpenClass but the same annotation in debug is marked with #OpenClass. In build.gradle we designated that annotation as the signal to the kotlin-allopen plugin. So any class annotated with #OpenForTesting will be made open at compile-time but only on Debug builds.
I want to write unit tests (junit4) for my maven-plugin. All examples i found use "AbstractMojoTestCase" (junit3 :-(). To get rid of this i got answer here. But the problem is how Mojos get instantiated:
MyMojo myMojo = (MyMojo) lookupMojo( "touch", pom );
That means i need a pom for every test case - the pom is the tests input data. But is there a way to mock (i would use Mockito) the project model some how?
Could lookupMojo(String groupId, String artifactId, String version, String goal, PlexusConfiguration pluginConfiguration) be a good starting point? In this case i would mock "PlexusConfiguration", but what methods?
Some maven-plugin testing doku uses classes like "MavenProjectStub". But i can't get a consistent picture of how a mojo is created and to what intefaces it talks on creation.
A perfect solution would be if i could just
#inject
MyMojo testObject;
and just mock all the stuff it need to get it working (primary i need #Parameters)
Based on my experience writing Maven plugin, there are two levels of testing a plugin: via unit test (using mocks) and via integration tests (using the maven-invoker-plugin).
For the integration tests, the maven archetype for new maven plugins already provide a good example out of the box, just execute the following and have a look at it:
mvn archetype:generate \
-DgroupId=sample.plugin \
-DartifactId=hello-maven-plugin \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-plugin
By default you will get integration tests in a profile to start with. An example maven project will also be available (under src\it\simple-it\pom.xml) which can execute your plugin goals. What I suggest is also to enforce the result of your integration test via additional constraints in that pom.xml. For instance: you can add the Maven Enforcer Plugin rule to check against created files, if that makes sense for your plugin.
To answer more specifically to your question on how to write unit tests for custom maven plugins, this is the approach I'm using:
JUnit + Mockito.
Test case running using #RunWith(MockitoJUnitRunner.class)
Mock Maven specific classes (MavenProject, Log, Build, DependencyNode, etc.) using #Mock annotations
Initiate and link your mock objects in a #Before method (typically setUp() method)
Test your plugin :)
As an example, you might have the following mocked objects as class variable of your unit test:
#Mock
private MavenProject project;
#Mock
private Log log;
#Mock
Build build;
Then, in your #Before method you need to add a big of glue code as following:
Mockito.when(this.project.getBuild()).thenReturn(this.build);
For instance, I use to write some custom Enforcer Plugin rules, hence I need
#Mock
private EnforcerRuleHelper helper;
And in the #Before method:
Mockito.when(this.helper.evaluate("${project}")).thenReturn(this.project);
Mockito.when(this.helper.getLog()).thenReturn(this.log);
Mockito.when(this.project.getBuild()).thenReturn(this.build);
Mockito.when(this.helper.getComponent(DependencyGraphBuilder.class)).thenReturn(this.graphBuilder);
Mockito.when(this.graphBuilder.buildDependencyGraph(this.project, null)).thenReturn(this.node);
As such, it will be easy to use these mock objects into your tests. For instance, a must have first dummy test is to test it against an empty build as following (below testing a custom Enforcer rule):
#Test
public void testEmptyBuild() throws Exception {
try {
this.rule.execute(this.helper);
} catch (EnforcerRuleException e) {
Assert.fail("Rule should not fail");
}
}
If you need to test against dependencies of your build, for instance, you might end up writing utility methods as following:
private static DependencyNode generateNode(String groupId, String artifactId, String version) {
DependencyNode node = Mockito.mock(DependencyNode.class);
Artifact artifact = Mockito.mock(Artifact.class);
Mockito.when(node.getArtifact()).thenReturn(artifact);
// mock artifact
Mockito.when(artifact.getGroupId()).thenReturn(groupId);
Mockito.when(artifact.getArtifactId()).thenReturn(artifactId);
Mockito.when(artifact.getVersion()).thenReturn(version);
return node;
}
In order to easily create dependencies into the dependency graph of your build, as following:
List<DependencyNode> nodes = new ArrayList<DependencyNode>();
nodes.add(generateNode("junit", "junit", "4.12"));
Mockito.when(node.getChildren()).thenReturn(nodes);
NOTE: you can improve the utility method if you need further details (like scope or classifier for a dependency).
If you also need to mock configuration of a plugin, because you need to scan existing plugins and their configuration, for instance, you can do it as following:
List<Plugin> plugins = new ArrayList<Plugin>();
Plugin p = new Plugin(); // no need to mock it
p.setArtifactId("maven-surefire-plugin");
Xpp3Dom conf = new Xpp3Dom("configuration");
Xpp3Dom skip = new Xpp3Dom("skip");
skip.setValue("true");
conf.addChild(skip);
p.setConfiguration(conf);
plugins.add(p);
Mockito.when(this.build.getPlugins()).thenReturn(plugins);
I will obviously not cover all the possible cases, but I am sure you got an understanding about approach and usage. Hope it helps.
How to unit test private (means with package visibility) classed in java?
I have a package, only one class is public in this package, other classes are private. How to cover other classed with unit tests? I would like to include unit tests in resting jar.
Create the unit test class in the same package.
For example, If com.example.MyPrivateClass located in src/main/java/com/example/MyPrivateClass.java
Then the test class will be in same package com.example.MyPrivateClassTestCase and will be located in src/test/java/com/example/MyPrivateClassTestCase.java
There are two ways to do this.
The standard way is to define your test class in the same package of the class to be tested. This should be easily done as modern IDE generates test case in the same package of the class being tested by default.
The non-standard but very useful way is to use reflection. This allows you to define private methods as real "private" rather than "package private". For example, if you have class.
class MyClass {
private Boolean methodToBeTested(String argument) {
........
}
}
You can have your test method like this:
class MyTestClass {
#Test
public void testMethod() {
Method method = MyClass.class.getDeclaredMethod("methodToBeTested", String.class);
method.setAccessible(true);
Boolean result = (Boolean)method.invoke(new MyClass(), "test parameter");
Assert.assertTrue(result);
}
}
As indicated in #Kowser's answer, the test can be in the same package.
In Eclipse, and I assume other IDEs, one can have classes in different projects but in the same package. A project can be declared to depend on another project, making the other project's classes available. That permits a separate unit test project that depends on the production project and follows its package structure, but has its own root directory.
That structure keeps the test code cleanly separated from production code.