Scala学习整理[第十四章 测试]<Programming In Scala>

第十四章 断言和单元测试

Scala自身具有断言assert和ensuring语句 ,还可以引入Junit进行测试(JVM语言 完美融合)

同时还有ScalaTest(需要自己下载)工具包 ,提供了更多更详尽的测试方法 ,这里只是简单的应用

package SecondWithProgrammingInScala

/**
  * 断言和单元测试
  * 基本的使用方法
  */
object Basic {
  def main(args: Array[String]): Unit = {
    //assert语句
    val a = 1
    val b = 2
    //断言失败会抛出java.lang.AssertionError: assertion failed
    //assert(a>b)
    assert(a < b)

    //ensuring函数 可适用于各种类型 ,使用了隐式转换 ,通过传入一个判断函数来检查
    if (a > b) {
      Array("Yes", "a<b")
    } else {
      Array("No")
    } ensuring (_.length > 1)
  }
}

/**
  * 使用Junit
  */

import junit.framework.TestCase
import junit.framework.Assert.assertEquals
import junit.framework.Assert.fail

class JunitTest extends TestCase {
  def testA(): Unit = {
    assertEquals(1, 1)
    try {
      1 / 0
      fail()
    } catch {
      case e: Exception => println(e)
    }
  }
}

/**
  * 使用较新的ScalaTest 3.01( scala版本要对应 )
  * 这里只简单的应用
  */

import org.scalatest.FunSuite

class SetFuncSuite extends FunSuite {
  //差集
  test("Test difference") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a -- b === Set("a", "c"))
  }

  //交集
  test("Test intersection") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a.intersect(b) === Set("b"))
  }

  //并集
  test("Test union") {
    val a = Set("a", "b", "a", "c")
    val b = Set("b", "d")
    assert(a ++ b === Set("a", "b", "c", "d"))
  }
}

/**
  * [ScalaTest使用](http://www.scalatest.org/quick_start)
  * 行为驱动开发(BDD behavior-driver development)的测试风格中
  * 使得测试代码趋于语言式
  */

import collection.mutable.Stack
import org.scalatest._

class ExampleSpec extends FlatSpec with Matchers {

  "A Stack" should "pop values in last-in-first-out order" in {
    val stack = new Stack[Int]
    stack.push(1)
    stack.push(2)
    stack.pop() should be(2)
    stack.pop() should be(1)
  }

  it should "throw NoSuchElementException if an empty stack is popped" in {
    val emptyStack = new Stack[Int]
    a[NoSuchElementException] should be thrownBy {
      emptyStack.pop()
    }
  }
}

/**
  * ScalaTest提供了较为详尽的测试方法 ,还有不同风格(类似Spec)的测试方法
  * 需要单独去理解学习
  */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值