简体   繁体   中英

PowerMock in Scala: java.lang.NullPointerException when getPackage

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]   ...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM