How to jmock Final class - junit

I was trying to mock final class(AnyFinalClass.java) in junit using JDave in eclipse.
public void setUp() throws Exception {
Mockery mockery = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
AnyFinalClass any = mockery.mock(AnyFinalClass.class);
}
I am trying to use jdave-unfinalizer-1.1.jar as javaagent but didnt had any success. I tried multiple things but getting following exception
java.lang.IllegalArgumentException: Cannot subclass final class class AnyFinalClass
at net.sf.cglib.proxy.Enhancer.generateClass(Enhancer.java:446)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25)
Can someone who has already tried jdave unfinalizer give me exact step how to make it work on eclipse.
I set following in eclipse.ini file but got the problem
-Xbootclasspath/a:lC:\WS\JunitTesting\jars\asm-3.0.jar
-javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
While running executing the junit, I gave vm argument as
javaagent:C:\WS\JunitTesting\jars\jdave-unfinalizer-1.1.jar
I am not sure what will be the code. jdave is not having the code and its site is pointing to some other site which is not working. Please correct my code or provide your same working code.
Any help is highly appreciated.

from Enhancer.java line 446:
if (TypeUtils.isFinal(sc.getModifiers()))
throw new IllegalArgumentException("Cannot subclass final class " + sc);
I have not worked with JDave but with another mocking frameworks and the only one that allows to mock a final class was powermock
Look also here

In order to get unfinalizer running you have to put -javaagent:path_to_unfinalizer/jdave-unfinalizer-1.1.jar in the VM arguments of the run configuration of the test.
I also had to include several dependencies of jdave-unfinalizer in the classpath of the project from which the tests ar being launched. These are, taken from the maven definitions of jdave:
jdave-core 1.1
cglib-nodep 2.1_3
objenesis 1.0
asm 3.0
asm-commons 3.0
asm-tree 3.0

Related

Any() method fails to compile in Java 1.8 with Mockito 1.10.9

My below code works well with Java 1.7 and Mockito version is 1.10.19.
#Test
public void populateUsersEmpty() {
// arrange
List<UserDTO> users = new ArrayList<UserDTO>();
// act
requestBuilder.populateUsers(mxsMessageOutMock, users);
// assert
verify(mxsMessageOutMock, times(0)).addRecordSet(CreateNewAlertRequestBuilder.MXS_RECORDSETNAME_USERS);
verify(mxsMessageOutMock, times(0)).addFieldNewRecord(anyString(), anyString());
verify(mxsMessageOutMock, times(0)).addField(anyString(), any());
}
But when I moved to Java 1.8 with same version of Mockito it started showing below error (bold letters). When I checked Mockito website I found that Mockito 3 yet to support java 8. If yes,then what is solution for this? Should I have to wait for their release or Is there any way to fix this. I tried passing AnyString() in place of any() but my code breaks still. Even anyObject() didn't help me.
verify(mxsMessageOutMock, times(0)).addField(anyString(), anyString());
CreateNewAlertRequestBuilderTest.java:436:0::0 The method addField(String, String) is ambiguous for the type IMXSMessageOut
[ant:iajc] [error 7]: error at verify(mockMessageOut, times(0)).addField(anyString(), any());
I understand that Its difficult to suggest without full code but here what I could share piece of code.
any(String.class)? if addField is accepting String, String why don't u use anyString(), anyString()

Problems Testing Sling Model with Custom Injectors

I've been doing some work with sling models for a project and in the process created a couple of custom injectors. Everything seems to work great when implemented (used in AEM). However, when I'm testing the custom injectors are not getting run.
Here's an example of what I currently have set up
In MyModel
#Inheritable
#CustomAnnotation("foo")
private String _foo
In test (tests using wcm.io mocking Libraries)
#Rule
AemContext context = new AemContext(ResourceResolverType.RESOURCERESOLVER_MOCK);
//required by the injector
#Mock
InheritanceService _inheritanceService;
#Mock
InheritableInjector _inheritanceInjector;
#Before
public void setup() {
context.registerService(InheritanceService.class, _inheritanceService);
context.registerService(InheritableInjector.class, _inheritanceInjector);
context.addModelsForPackage("com.package.example.models");
//use this resource in tests to adaptTo(MyModel.class)
_resource = context.load().json("myJson.json", "/myPath");
}
... tests
The tests compile and run, but the Injector isn't being executed. I know it's registered because when I don't have the Injector's dependent services registered in the context I get an error. When I debug through it, none of the breakpoints are hit. I'm wondering if I need to also register the "Inheritable" annotation somewhere or if anyone just has any general information on how I can get the custom injector to execute.
thank you
I was able to figure out my error. So the important thing to remember about Sling Model Injectors is that they are just OSGI services (something I completely let myself get away from).
So just treating them like normal services and then remembering to annotate the Injector with #InjectMocks was what I needed to do in order to fix the error.
The following now works great.
#Mock
InheritanceService _inheritanceService; //injector dependency
#InjectMocks
InheritanceInjector _inheritanceInjector;
#Before
public void setup() {
context.registerService(InheritanceService.class, _inheritanceService);
context.registerService(InheritableInjector.class, _inheritanceInjector);
}
hopefully that helps anyone that might run into the issue. If anyone can make this answer better please feel free to reply/edit.

Jodd proxy Unable to install breakpoint due to missing line number attributes

I have a jodd project that uses Proxetta and JTX for creating transactions over services classes. The issue is that when I try to debug a service class I receive :
Unable to install breakpoint due to missing line number attributes
I suspect that there has something to do with they way Proxetta generates my proxies classes as it seems that in Spring if you have no interface for a class the same happens.
I use Eclispe and here how Proxetta is initialized:
public void initProxetta() {
ProxyAspect txServiceProxy = new ProxyAspect(AnnotationTxAdvice.class,
new MethodAnnotationPointcut(Transaction.class) {
#Override
public boolean apply(MethodInfo mi) {
return isPublic(mi) &&
isTopLevelMethod(mi) &&
matchClassName(mi, "*ServiceImpl") &&
super.apply(mi);
}
});
proxetta = ProxyProxetta.withAspects(txServiceProxy);
proxetta.setClassLoader(this.getClass().getClassLoader());
}
Would you please try the following quickstart webapp1 example?
Its gradle project, so you can quickly import it in any IDE. In this example, we create proxy almost exactly like you above, but on actions (which should not make a difference). Now try to put a breakpoint into the IndexAction - this one gets proxified, for example. I am able to put break point there in IntelliJ IDEA.
Moreover, I dunno why Eclipse complains about the breakpoint in the service implementation class, since Proxetta as you used above creates a proxy subclass, and does not change the target class in any way. So when you put breakpoint in the service implementation code, it is in your class, not proxy class.
Finally, did you put BP on the method, or inside the code? If it is the first (on the method), then please try to put the BP inside the code of your service: eg on first line of the method body.

Class loading collision between Robolectric and Powermock

I'm trying to write a test that needs both Robolectric 2.2 and PowerMock, as the code under test depends on some Android libraries and third party libraries with final classes that I need to mock.
Given that I'm forced to use the Robolectric test runner through:
#RunWith(RobolectricTestRunner.class)
...I cannot use the PowerMock test runner, so I'm trying to go with the PowerMock java agent alternative, without luck so far.
I have setup everything according to this guide but I'm facing a collision problem between classes required by the javaagent library and by robolectric through its dependency with asm-1.4. Both depend on
org.objectweb.asm.ClassVisitor
, but javaagent-1.5.1 ships with its own version where ClassVisitor is an interface while asm-1.4 version for the same namespace is an abstract class, with the corresponding error at runtime:
java.lang.IncompatibleClassChangeError: class org.objectweb.asm.tree.ClassNode has interface org.objectweb.asm.ClassVisitor as super class
I have even tried to modify the javaagent library jar to entirely remove the org.objectew.asm classes in there, but that doesn't work as ClassNotFoundException happens afterwards due to some other classes needed in the org.objectweb.asm package that only ship in the javaagent library jar, and not in the asm one.
Any ideas? According to examples out there the agent seems to work fine with, at least, the Spring test runner.
I had the same problem and while I didn't solve this problem as such, I wanted to share my approach, which removes the need for PowerMock (which is always a good thing in my view): I wanted to mock a call to
Fragment fooFragment = new FooFragment();
So what I did was addanother level of indirection. I created a FragmentProvider class:
public FragmentFactory fragmentFactory = new FragmentFactory();
[...]
Fragment fooFragment = fragmentFactory.getFooFragment();
After i did this, I could just mock out the factory with standard Mockito, like this:
FragmentFactory mockFactory = mock(FragmentFactory.class);
activity.fragmentFactory = mockFactory;
when(mockFactory.getFooFragment()).thenReturn(mockFooFragment);

Want to use JUnit in Domino Designer / Java Beans - but keep getting a "Class not found" error?

I do the following:
From the Package Explorer I select "New, Other, JUnit Test Case"
I write this code:
package dk.sample;
import org.junit.*;
import static org.junit.Assert.*;
public class TestCase {
#Test
public void alwaysTrue(){
assertTrue( true );
}
}
I then select "Run As, JUnit test"
Get this error: "Class not found dk.sample.TestCase
java.lang.ClassNotFoundException: ...."
What do I miss? Have tried with different Run Configurations - but it seems like I miss a classpath somewhere? But to what and where?
To make JUnit work within Domino Designer you need to perform few additional steps:
set up source control for your application
adjust the on-disk project to be recognized as Java application
run JUnit tests within your on-disk project
Please note that java agents have to be tested in a different way..
You can find more detailed explanation about enabling JUnit for both XPages and Agents in the following blog post: Unit Tests for Lotus Domino Applications
Here's also a great how-to on this topic.
Coundn't get JUnit to work inside the Domino Designer. Instead of running the tests from DDE, I now run the tests from a XPages. This works like a dream. Made my own 'JUnit runner' class - that is, I just call the JUnit runners but handles the result my self in order to display it as html on the XPage.
Code can be found here: http://xpages.dk/wp-content/uploads/2013/10/junitrunner.txt
Danish blog post here: http://xpages.dk/?p=1162