Scala的单元测试

来源:互联网 发布:java多线程编程 pdf 编辑:程序博客网 时间:2024/06/10 16:10

Scala有着自己的单元测试,当然它也可以使用java的junit等单元测试

1、准备工作

你根据你需要的版本去下载单元测试的jar包(点击进入下载地址,从maven上面下载)

测试用例代码

class TestUtils {  def Add(i:Int,j:Int):Int ={    i+j  }}

2、单元测试

2.1 Suit单元测试

测试代码
import org.scalatest.Suite/**  * Created by LiuWenSheng on 2017/8/15.  * ScalaTest 提供了若干编写测试的方法,最简单的就是创建扩展 org.scalatest.Suite的类  * 并在这些类中定义测试方法。Suite代表一个测试集。测试方法名要以“test”开头。execute方法可以在Suit子类中重载。  *  */class ForTest1 extends  Suite{  def test_Add() ={    val util = new TestUtils    print(util.Add(1,2))  }}

2.2FunSuit单元测试

import org.scalatest.FunSuite/**  * Created by LiuWenSheng on 2017/8/15.  * ScalaTest提供了名为FunSuit的特质重载了execute方法从而可以用函数值的方式  * 而不是方法定义测试  */class ForTest2 extends  FunSuite{  /**    * test后面圆括号()内为测试名称,可以使用任何字符串,不需要传统的驼峰形式命名。    * !!!!!!!但是名称需要唯一!!!!!!!!!!!    * 圆括号后面的大括号{}之内定义的为测试代码。被作为传名参数传递给test函数,由test登记备用    */  test("这是测试名称"){    //测试代码    val test1 = new TestUtils;    print(test1.Add(3,4))  }}
这里涉及的传名参数你可能还不知道是什么下面的例子简单介绍一下传名参数

object NameFunction {  def main(args: Array[String]) {    myPrintFunction(add(1,2))  }  def myPrintFunction(i: =>Int): Unit ={    println("这是一个使用传名参数的函数")    println("传名参数i的值为:"+i)  }  def add(i:Int,j:Int): Int ={    println("即将输出i+j")    i+j  }}
输出结果为

这是一个使用传名参数的函数即将输出i+j传名参数i的值为:3
这是因为myPrintFunction函数运行时首先执行了第一个println函数这时,他还不知道传来的是什么值,于是就去执行add函数,得到参数 i 的值然后执行第三个println函数
可以看出传名参数的不以这样的地方为 def myPrintFunction(i: =>Int): Unit ={ ...}

如果你需要测试异常的抛出情况


import java.io.IOExceptionimport org.scalatest.FunSuiteclass TestUtilSuit extends  FunSuite{  test("get execption"){    intercept[IOException]{      val a = 1/0    }  }}
这里我期望的是抛出IOExexeption但是实际上抛出了ArithmeticException异常所以后台控制台就会报出错误信息如下:

Expected exception java.io.IOException to be thrown, but java.lang.ArithmeticException was thrown.ScalaTestFailureLocation: TestUtilSuit$$anonfun$2 at (ForTest2.scala:21)org.scalatest.exceptions.TestFailedException: Expected exception java.io.IOException to be thrown, but java.lang.ArithmeticException was thrown.at org.scalatest.Assertions$class.newAssertionFailedException(Assertions.scala:496)at org.scalatest.FunSuite.newAssertionFailedException(FunSuite.scala:1555)
提示一下,如果大括号之间的代码被一个参数指定的异常类的实例突然中断,intercept 将返回捕获的异常,以便于之后进行检查。另一方面,如果代码没有抛出异常,或抛出了不同的异常,intercept将抛出 AssertionError,并且将在失败报告中得到错误消息。


还有其它很不错的方法,我看到别人写的一个很不错的博客(点击进入)大家感兴趣可以参考一下



原创粉丝点击