如何使用PowerMock模拟SBT项目中的最终类

时间:2013-08-20 17:13:50

标签: scala sbt powermock

PowerMock没有ScalaTest支持,所以我正在尝试使用JUnit来运行我的ScalaTest类,使用@RunWith[classOf[JUnitRunner]]。使用Maven,您可以配置javaagent模块以急切加载以支持此功能,详见the PowerMock wiki。我需要在SBT中做些什么来获得相同的结果?

name := "my-project"

version := "1.0"

scalaVersion := "2.10.2"

libraryDependencies ++= Seq(
    // ... other dependencies above ...
    "org.powermock" % "powermock-api-mockito" % "1.5.1" % "test",
    "org.powermock" % "powermock-module-javaagent" % "1.5.1" % "test",
    "org.powermock" % "powermock-module-junit4-rule-agent" % "1.5.1" % "test",
    "com.novocode" % "junit-interface" % "0.10" % "test->default"
)

如图所示,该项目有错误:

[error] Caused by: java.lang.IllegalStateException: PowerMockRule can only be used with the system classloader but was loaded by sbt.classpath.ClasspathUtilities$$anon$1@1cee593
[error]     at org.powermock.modules.junit4.rule.PowerMockRule.<clinit>(PowerMockRule.java:28)
[error]     ... 55 more

看来SBT有自己的类加载器用于运行与PowerMock需要做的事情相冲突的测试。

1 个答案:

答案 0 :(得分:1)

使用SBT 0.12.4,将以下内容添加到build.sbt

fork in Test := true

javaOptions in Test <+= managedClasspath in Test map { (cp: Classpath) =>
  val agentJar = cp.find(_.data.name.contains("powermock-module-javaagent")).get
  "-javaagent:" + agentJar.data
}

这会导致SBT创建一个用于运行测试的新JVM进程,并添加正确的JVM命令行参数以预加载javaagent模块。