遇到比较奇怪的问题,mvn项目中的main函数可以正常运行,但是test阶段出错,报错信息如下:

Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$000(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at learning_scala.java.Main.main(Main.java:12)
Caused by: java.lang.ClassNotFoundException: scala.ScalaObject
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)

test代码如下:

class Sampling$Test extends FunSpec{
  describe("Sampling Test"){
    val spark = SparkSession
      .builder()
      .master("local")
      .getOrCreate()
    println("......")
    it("should run without exeption."){
      val array: Array[String] = Array("down", "xxx", "xxx", "xxx", "xxx")
      Sampling.main(array)
    }
  }
}

解决方法:

将 scala-library.jar 的路径加入到 CLASSPATH 中(参考:https://stackoverflow.com/questions/7781547/noclassdeffounderror-scala-scalaobject-in-mixed-scala-java-project),但是又报了如下错误:

Error:scalac: error while loading Suite, Scala signature Suite has wrong version
 expected: 5.0
 found: 4.1 in Suite.class

 是scala和单元测试包不匹配造成的,将org.specs包更新到最新,问题解决:

<dependency>
      <groupId>org.specs</groupId>
      <artifactId>specs</artifactId>
      <version>1.4.3</version>
      <scope>test</scope>
</dependency>