samedi 24 janvier 2015

Powermock not intercepting new object creation

I am attempting to test a method that creates a new instance of another class that I wish to mock using powermock. My code (simplified) is as follows -


Testing code:



import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.easymock.EasyMock.anyObject;
import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest( { ClassUnderTest.class } )
public class TestForClassUnderTest {

private ClassToBeMocked classToBeMocked;
private ClassUnderTest classUnderTest;

public void testSimple() throws Exception {

classToBeMocked = createMock(ClassToBeMocked.class);
// trying to intercept the constructor
// I *think* this is the root cause of the issue
expectNew(ClassToBeMocked.class, anyObject(), anyObject(), anyObject()).andReturn(classToBeMocked);

classToBeMocked.close();
expectLastCall();
replayAll();

// call to perform the test
classUnderTest.doStuff();
}
}


Code that is being tested:



import ClassToBeMocked;

public class ClassUnderTest {
private ClassToBeMocked classToBeMocked;

public void doStuff() {

classToBeMocked = new ClassToBeMocked("A","B","C");
// doing lots of other things here that I feel are irrelevant
classToBeMocked.close();
}
}


Code that I wish to mock:



public class ClassToBeMocked {
public ClassToBeMocked(String A, String B, String C) {
// irrelevant
}
private close() {
// irrelevant
}
}


The error I get is as below:



java.lang.ExceptionInInitializerError

at ....more inner details of where this goes into

at ClassToBeMocked.close

at ClassUnderTest.doStuff

at TestForClassUnderTest.test.unit.testSimple

Caused by: java.lang.NullPointerException


PowerMock version:1.4.5


EasyMock version: 3.1


PS: I have stripped down the code to bare minimums, only showing the details of the mocking library, let me know if you think my other code is somehow interfering and I can give more details on the bits you think are important to show. Any links to other examples doing this may even help.


Aucun commentaire:

Enregistrer un commentaire