My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
FAQ  

faq
Updated Jan 5, 2012 by johan.ha...@gmail.com

Frequently asked questions

  1. PowerMockRunner throws a
  2.   java.lang.NoClassDefFoundError: org/junit/internal/runners/BeforeAndAfterRunner
or
java.lang.SecurityException: class "org.junit.internal.runners.TestClass"'s signer information does not match signer information of other classes in the same package
exception. What's wrong?
You're probably using the wrong PowerMockRunner. There's one runner made for JUnit 4.4 and above and a second runner made for JUnit 4.0-4.3 (although the latter also works for some older minor versions of JUnit 4.4). Try switching from the org.powermock.modules.junit4.PowerMockRunner to org.powermock.modules.junit4.legacy.PowerMockRunner or vice versa. Look at the getting started guide to see how to configure this in maven.
  1. Cobertura gives me errors or produces strange results when running PowerMock tests in Maven, how do I solve this?
  2. Either:
    1. Upgrade to Cobertura 2.4+ or,
    2. Follow the instructions on this blog or,
    3. Add the following to your pom.xml file:
    4.  <build>
        <plugins>
           <plugin>
              <artifactId>maven-surefire-plugin</artifactId>
              <configuration>
                  <forkMode>pertest</forkMode> 
              </configuration>
            </plugin>
           </plugins>
        </build>
  3. I get a ClassCastException from DocumentBuilderFactory, SaxParserFactory or other XML related classes
  4. The reason is that the XML framework tries to instantiate classes using reflection and does this from the thread context classloader (PowerMock's classloader) but then tries to assign the created object to a field not loaded by the same classloader. When this happens you need to make use of the @PowerMockIgnore annotation to tell PowerMock to defer the loading of a certain package to the system classloader. What you need to ignore is case specific but usually it's the XML framework or some packages that interact with it. E.g. @PowerMockIgnore({"org.xml.*", "javax.xml.*"}). Another option would be to try to bootstrap using our Java Agent.
  5. I cannot mock classes in from java.lang, java.net, java.io or other system classes, why?
  6. This is because they're loaded by Java's bootstrap classloader and cannot be byte-code manipulated by PowerMock's classloader. Since PowerMock 1.2.5 there's a work-around, please have a look at this simple example to see how it's done.
  7. When mocking Hibernate you get an error similar to:
  8. java.lang.ClassCastException: org.hibernate.ejb.HibernatePersistence cannot be cast to javax.persistence.spi.PersistenceProvider
        at javax.persistence.Persistence.findAllProviders(Persistence.java:80)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:49)
        at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
        ...
    Solution: Upgrade to PowerMock 1.3+ or use @PowerMockIgnore("javax.persistence.*") at the class-level of your test.
  9. When running a PowerMock test log4j gives me the following (or something similar) error, what now?
  10. log4j:ERROR A "org.apache.log4j.xml.DOMConfigurator" object is not
    assignable to a "org.apache.log4j.spi.Configurator" variable.
    log4j:ERROR The class "org.apache.log4j.spi.Configurator" was loaded
    by
    log4j:ERROR [org.powermock.core.classloader.MockClassLoader@14a55f2]
    whereas object of type
    log4j:ERROR "org.apache.log4j.xml.DOMConfigurator" was loaded by
    [sun.misc.Launcher$AppClassLoader@92e78c].
    log4j:ERROR Could not instantiate configurator
    [org.apache.log4j.xml.DOMConfigurator].
or
Caused by: org.apache.commons.logging.LogConfigurationException:
Invalid class loader hierarchy.  You have more than one version of
'org.apache.commons.logging.Log' visible, which is not allowed.
There are a couple of different solutions to this:
  1. Upgrade to PowerMock 1.3+
  2. Make use of the @PowerMockIgnore annotation at the class-level of the test. For example if using log4j, use @PowerMockIgnore("org.apache.log4j.*") if using commons logging, use @PowerMockIgnore("org.apache.commons.logging.*").
  3. Add -Dlog4j.ignoreTCL=true as VM-Arguments to your test-run-configuration.
  4. If you're using PowerMock 1.1 or above you should use the @MockPolicy annotation and specify a mock policy. For example if you're using slf4j in combination with log4j use @MockPolicy(Slf4jMockPolicy.class) or if you're using Log4j stand-alone use @MockPolicy(Log4jMockPolicy.class). This is the recommended way. For example:
  5. @RunWith(PowerMockRunner.class)
    @MockPolicy(Log4jMockPolicy.class)
    public class MyTest {
    
    }
  6. Create a nice mock of the Logger class and set the the Logger field to this instance. If the field is static suppress the static initializer for the class (using the @SuppressStaticInitializerFor annotation) and then set the logger field to the mock you just created. Next prepare the org.apache.log4j.Appender for testing using the @PrepareForTest annotation. For example:
  7. @RunWith(PowerMockRunner.class)
    @SuppressStaticInitializationFor("org.myapp.MyClassUsingLog4J")
    @PrepareForTest( { Appender.class })
    public class MyTest {
    
      @Before
      public void setUp() {
          Logger loggerMock = createNiceMock(Logger.class);
          Whitebox.setInternalState(MyClassUsingLog4J.class, loggerMock);
          ...
      }
      ...
    }
  8. Follow the same procedure as in the previous step but instead of adding the org.apache.log4j.Appender class to the @PrepareForTest annotation you add "org.apache.log4j.LogManager" to the @SuppressStaticInitializerFor annotation. For example:
  9. @RunWith(PowerMockRunner.class)
    @SuppressStaticInitializationFor( {
    		"org.myapp.MyClassUsingLog4J",
    		"org.apache.log4j.LogManager" })
    public class MyTest {
    
      @Before
      public void setUp() {
          Logger loggerMock = createNiceMock(Logger.class);
          Whitebox.setInternalState(MyClassUsingLog4J.class, loggerMock);
          ...
      }
      ...
    }
  10. You could try using the @PrepareEverythingForTest annotation (not recommended).
  1. Does PowerMock work with TestNG?
  2. Yes, since version 1.3.5 PowerMock does have basic TestNG support.
  3. Is PowerMock a fork of EasyMock?
  4. No. PowerMock extends other mock frameworks such as EasyMock with powerful capabilities such as static mocking.
  5. Can you use PowerMock with other frameworks that uses a JUnit runner?
  6. Yes, you can make use of the PowerMockRule.
Comment by robinson...@gmail.com, Apr 16, 2009

I am trying to use a PowerMock? class along with Fitenesse, although the code executes as expected when executed as a Junit, when used via fitnesse the original static methods which is mocked @SuppressStaticInitializerFor? is been called, any advice ?

Comment by project member johan.ha...@gmail.com, Apr 25, 2009

Please send your question to the mailing-list by joining our google group.

Comment by arseniy....@gmail.com, May 6, 2009

I get: Could not create and run test suite: java.lang.ClassCastException?: org.powermock.api.easymock.mockpolicies.Log4jMockPolicy? when trying to use this mock policy to suppress log4j errors

Comment by project member johan.ha...@gmail.com, May 16, 2009

Try to use @PowerMockIgnore?(org.apache.log4j") instead

Comment by SemenYu...@gmail.com, Jul 15, 2009

Hi,

I tried PowerMock?, but I can't start my Application. It uses JacORB and I need to start all application for checking some especial flows. But my application can't start because I gives exception like

org.omg.CORBA.INITIALIZE: can't instantiate default ORB implementation org.jacorb.orb.ORB vmcid: 0x0 minor code: 0 completed: No

at org.omg.CORBA.ORB.create_impl(Unknown Source) at org.omg.CORBA.ORB.init(Unknown Source)
...
at org.junit.internal.runners.MethodRoadie?.runBefores(MethodRoadie?.java:129) at org.junit.internal.runners.MethodRoadie?.runBeforesThenTestThenAfters(MethodRoadie?.java:93) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$2.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:212) at org.junit.internal.runners.MethodRoadie?.runTest(MethodRoadie?.java:84) at org.junit.internal.runners.MethodRoadie?.run(MethodRoadie?.java:49) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:205) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:159) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:133) at org.junit.internal.runners.ClassRoadie?.runUnprotected(ClassRoadie?.java:34) at org.junit.internal.runners.ClassRoadie?.runProtected(ClassRoadie?.java:44) at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:131) at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:112) at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner?.run(AbstractCommonPowerMockRunner?.java:44) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45) at org.eclipse.jdt.internal.junit.runner.TestExecution?.run(TestExecution?.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner?.runTests(RemoteTestRunner?.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner?.runTests(RemoteTestRunner?.java:673) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner?.run(RemoteTestRunner?.java:386) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner?.main(RemoteTestRunner?.java:196)
Caused by: java.lang.ClassCastException?: org.jacorb.orb.ORB cannot be cast to org.omg.CORBA.ORB
... 29 more

What can you recommend me?

Comment by project member johan.ha...@gmail.com, Jul 15, 2009

Please join and use our mailing-list (powermock at googlegroups.com) instead of posting questions here.

Comment by astrophy...@gmail.com, Feb 3, 2010

hi, am new to powermock. when i tried using it am getting the below error. any suggestion would be great.

java.lang.LinkageError?: Class org/easymock/IMocksControl violates loader constraints

Comment by project member johan.ha...@gmail.com, Feb 3, 2010

Please post an example on the mailing-list (powermock at googlegroups.com).

Comment by adrian.p...@gmail.com, Mar 22, 2010

For #4 I find that I need to wildcard the package name like so :

@PowerMockIgnore( { "org.apache.commons.logging.*", "org.apache.log4j.*" })
Comment by project member johan.ha...@gmail.com, Mar 22, 2010

That's correct, thanks for spotting it.

Comment by muthuraj...@gmail.com, May 26, 2010

hi ,

i mock the constructor

new FindProgramHelper?().find(settop, criteria, null);

like this PowerMock?.createMockAndExpectNew(FindProgramHelper?.class); EasyMock.expect(findPgm.find(p1,p2,p3)).andReturn(value); PowerMock?.replay(FindProgramHelper?.class);

EasyMock.replay(findPgm);

but they using two different constructor for calling different method of same class like this

int value = new FindProgramHelper?().find(p1,p2,p3); int v2 = new FindProgramHelper?().findScheduleTimes(p1,p2);

so i try this way

PowerMock?.createMockAndExpectNew(FindProgramHelper?.class); EasyMock.expectLastCall().anyTimes();

EasyMock.expect(findPgm.find(p1,p2,p3)).andReturn(value); EasyMock.expect(findPgm.findScheduleTimes(p1,p2)).andReturn(value);
PowerMock?.replay(FindProgramHelper?.class);
EasyMock.replay(findPgm);

but it showing error

java.lang.AssertionError?:

Unexpected method call findScheduleTimes(p1,p2):
at org.easymock.internal.MockInvocationHandler?.invoke(MockInvocationHandler?.java:32)

please tell me

how can i mock this to tackle the two different constructor of same class .

Comment by muthuraj...@gmail.com, Jun 2, 2010

hi,

My junit test class MyclassTest?.java having 20 testcase1().. methods

i execute the one testcase1() just select and right click to execute that.

But i try to execute the only 5 test method instead of 20,it is not getting executed .how can i execute that (without @ignore option in other method)

using eclipse

thank you

Comment by project member johan.ha...@gmail.com, Aug 28, 2010

Please use the mailing list instead of asking questions here.

Comment by leonardo...@gmail.com, Oct 25, 2010

Do you have plans to support JMock?

Comment by jrh...@gmail.com, Dec 2, 2010

>> I cannot mock classes in from java.lang, java.net, java.io or other system classes, why?

Is this outdated? I've successfully mocked java.net.URI and java.net.URL objects.

Comment by project member johan.ha...@gmail.com, Dec 5, 2010

leonardovarela: It would be really cool and I've thought about it but I just don't have time to do it. But if you want to mock final classes in JMock today you can still use PowerMock? for it. Just depend on powermock-core and prepare the final class for test.

Comment by project member johan.ha...@gmail.com, Dec 5, 2010

jrh3k5: It works, but you need to prepare the class calling the URL object, not the URL object itself.

Comment by sri.nara...@gmail.com, Mar 16, 2011

Hi I am trying to unit test a servlet using powermock easymock , but getting an exception in the createmock of ServletRequest? java.lang.ClassFormatError?: Absent Code attribute in method that is not native or abstract in class file javax/servlet/http/Cookie

@PrepareForTest?(IdGenerator?.class) @RunWith?(PowerMockRunner?.class) public class TestSipServlet?

{

@Test public void testDoGet() throws Exception {
final HttpServletRequest? request = createMock(HttpServletRequest?.class);
}

}

Comment by info.ame...@gmail.com, May 16, 2011

Hi, there is another possible solution for the Log4J error. Add -Dlog4j.ignoreTCL=true as VM-Arguments (also possible with ant vmargs) to your test-run-configuration. this will stop log4j that something is wrong, and will output all logging as expected (note: this is the log4j autoconfiguration, the console is possible not the same as you expect from your log4j.properties configuration, but enough for testing)

Hope this helps ;) and someone add's this to the FAQ.

Comment by art.mar...@gmail.com, Jun 3, 2011

Is there any possibility to mock only one public static method for public class (instances of this class can not be created!).

I have 'Helper' class with private constructor to ommit creation any instances of it. This class have many public static methods, but during the unit test I want to mock only one static method 'public static int make(String str, int a)' to return '10', but rest of the methods (about 23 methods) I want work normally 'CallRealMethod?'. I work with Mockito library.

Is there any simple possibility to obtain such functionality?

Comment by nicogonz...@gmail.com, Jun 27, 2011

Is it possible to use loggers in the test class itself?

e.g.:

public class MyTest {

    private static Logger logger = Logger.getLogger(MyTest.class);

If I use any of the available solutions for

When running a PowerMock?? test log4j gives me the following (or something similar) error, what now?

I don't get the logging error mentioned there, but I cannot have log entrances in my test clasess.

Any ideas? Regards, Nico


Sign in to add a comment
Powered by Google Project Hosting