目标

单机开发Spark,使用Scala语言,运行单元测试

新建测试程序代码

接续前文,继续添加一个测试scala程序
在src/test/文件夹下,右键,New->Directory,新建名为scala的文件夹,右键New->Scala Class,新建一个Class,名字随意,如test1

添加依赖

这里使用holden karau大神的测试库,在pom中添加依赖如下

  1. <dependency>
  2. <groupId>com.holdenkarau</groupId>
  3. <artifactId>spark-testing-base_2.11</artifactId>
  4. <version>2.4.0_0.11.0</version>
  5. </dependency>

编辑测试类的继承关系

这里先展示类名,是为了提示大家,Intellij IDEA是可以自动完成的,不只是类名,连需要import的类都会自动添加进来。

  1. class test1 extends FunSuite with SharedSparkContext{
  2. }

就是变成这样:

  1. import com.holdenkarau.spark.testing.SharedSparkContext
  2. import org.scalatest.FunSuite
  3. class test1 extends FunSuite with SharedSparkContext{
  4. }

设置环境变量

在项目文件列表中,src/test/scala/test1.scala点右键,Run test1,即可运行,只是有报错

  1. 19/04/22 14:33:44 WARN Shell: Did not find winutils.exe: {}
  2. java.io.FileNotFoundException: java.io.FileNotFoundException: HADOOP_HOME and hadoop.home.dir are unset. -see https://wiki.apache.org/hadoop/WindowsProblems

在右上角的绿色三角左侧,下拉菜单中,Edit Configuration,找到Environment variables,右侧点编辑,加入一行HADOOP_HOME目录,比如我的是

  1. HADOOP_HOME=C:\files\hadoop\311

这时还有一个native library的WARN,再加一行环境变量,就没了

  1. PATH=C:\files\hadoop\311\bin

添加简单的测试代码

非常基础,如下所示

  1. import com.holdenkarau.spark.testing.SharedSparkContext
  2. import org.scalatest.FunSuite
  3. class test1 extends FunSuite with SharedSparkContext{
  4. test("works, obviously!") {
  5. assert(1 == 1)
  6. }
  7. test("Words counting") {
  8. assert(sc.parallelize("Hello world My name is cd".split("\\W")).map(_ + 1).count == 6)
  9. }
  10. }