Scala写测试类

2016/11/20 posted in  Scala

Java中可以用Junit来写测试类,scala中当然也可以很方便的写测试类.
在日常开发中,我们应该按照规范多写测试类.也不是为了测试一个方法,就写一个main方法,这样太不专业了.

添加Scala测试类相关依赖

scalatest依赖

添加以下依赖后,然后就可以在类中继承FunSuite类,就可以写测试类了

        <dependency>
            <groupId>org.scalatest</groupId>
            <artifactId>scalatest_2.10</artifactId>
            <version>2.2.1</version>
            <scope>test</scope>
        </dependency>

scala测试报告插件

如果嫌麻烦也不用加下面的插件.插件写这里,这是为了做记录

<plugin>
<groupId>org.scalatest</groupId>
<artifactId>scalatest-maven-plugin</artifactId>
<version>1.0</version>
<configuration>
<reportsDirectory>${project.build.directory}/surefire-reports</reportsDirectory>
<junitxml>.</junitxml>
<filereports>WDF TestSuite.txt</filereports>
<argLine>-XX:MaxPermSize=256m -Xmx2g</argLine>
</configuration>
<executions>
<execution>
<id>test</id>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>


<plugin>
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>3.2.2</version>
        <configuration>
          <scalaVersion>${scala.complete.version}</scalaVersion>
          <javacArgs>
            <javacArg>-source</javacArg>
            <javacArg>${java.version}</javacArg>
            <javacArg>-target</javacArg>
            <javacArg>${java.version}</javacArg>
          </javacArgs>
        </configuration>
        <executions>
          <execution>
            <id>scala-compile</id>
            <phase>process-resources</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>scala-test-compile</id>
            <phase>process-test-resources</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

实践例子

import org.scalatest.{BeforeAndAfterAll, FunSuite, ShouldMatchers}

/**
  * Created by hushiwei
  * desc : scala tests
  */
class ScalaFunc extends FunSuite with BeforeAndAfterAll with ShouldMatchers{

  override def beforeAll(): Unit = {
    println("test case start...")
  }

  test("hello world"){
    val l1=List(1,2,3)
    val res=l1.flatMap(x=>x match{
      case 3=>List('a','b')
      case _ => List(x*2)
    })
    println(res)

    println("~"*50)
    val str="hello world"
    str should be ("hello world")
    assert(str.length==11)
  }

  override def afterAll(): Unit = {
    println("test case over...")
  }
}


注意:
1. 测试类必须是class,不能是object
2. beforeAll与afterAll都是可选的.
3. 与Junit都是类似的.