PowerMock in Scala: java.lang.NullPointerException

2019-06-13 01:02发布

问题:

This code just getPackage and getName of a class (not use any mock techniques yet), but it failed.

Anyone see this problem before?

Code:

import mai.MyScala1
import org.junit.Test
import org.junit.runner.RunWith
import org.powermock.modules.junit4.PowerMockRunner
import org.scalatest.junit.JUnitSuite

@RunWith(classOf[PowerMockRunner])
class MyTest extends JUnitSuite {

  @Test def test1() {
    classOf[MyScala1].getPackage          // this one returns null
    classOf[MyScala1].getPackage.getName  // raise java.lang.NullPointerException    
  }
}

Error logs:

[info] - test1 *** FAILED ***
[info]   java.lang.NullPointerException:
[info]   at org.apache.tmp.MyTest.test1(MyTest.scala:15)
[info]   at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[info]   at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[info]   at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[info]   at java.lang.reflect.Method.invoke(Method.java:497)
[info]   at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
[info]   at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:310)
[info]   at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
[info]   at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
[info]   at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
[info]   ...

回答1:

I think I found the answer, but I don't understand why it works?

Answer: Inside sbt, we should first "set fork := true", then everything will work fine.

The problem might be related to process vs thread problem.