scala单元测试,包括功能测试和性能测试

十分简单的scala单元测试

在编写性能要求高的模块的时候,单元测试是有必要的,通过搜索,我找到了一套提供单元功能测试和性能测试的可行方案,该方案简单好用,推荐给大家。

测试工具

首先找到适用于scala的好的测试工具是有必要的,通过搜索我找到了以下两个:

  1. scalaCheck:提供单元功能测试功能。
  2. scalaMeter:提供单元性能测试功能,测试局部代码的性能并给出报告。

这两个工具提供scala语言的api,集成和使用起来非常简单,下面就给出代码样例提供参考,首先找到需要的依赖包

sbt依赖:

"org.scalacheck" %% "scalacheck" % "1.14.0"% Test,
"com.storm-enroute" %% "scalameter" % "0.8.2" % Test

  

依赖包找到后根据官网提供的代码样例,我修改后用来测试不同序列化协议的序列化性能,这里主要测试json和protostuff。

代码样例

import java.sql.Timestamp

import org.json4s.jackson.Serialization.write
import org.scalameter.api._
import util.json.KafkaJsonFormat
import util.protostuff.ProtostuffUtil

case class SerialTestCase(a: String, b: Timestamp)

object TestPerf extends Bench.LocalTime {
  implicit val formats: KafkaJsonFormat.type = KafkaJsonFormat // Brings in default date formats etc.
  val y = "yisen"
  val sa = Array(SerialTestCase(y, new Timestamp(System.currentTimeMillis())),
    SerialTestCase(y, new Timestamp(System.currentTimeMillis())),
    SerialTestCase(y, new Timestamp(System.currentTimeMillis())),
    SerialTestCase(y, new Timestamp(System.currentTimeMillis())),
    SerialTestCase(y, new Timestamp(System.currentTimeMillis())))
  val indexes: Gen[Int] = Gen.range("model")(0, 4, 1)
  performance of "Range" in {
    measure method "json" in {
      using(indexes) in {
        r => {
          write(sa(r))
        }
      }
    }
  }
  performance of "Range" in {
    measure method "protostuff" in {
      using(indexes) in {
        r => {
          ProtostuffUtil.serialize(sa(r))
        }
      }
    }
  }
}

  

伴生类继承了Bench.LocalTime后就成为了可运行的scala类,直接运行,运行好后控制台会输出测试报告。

测试报告

::Benchmark Range.json::
cores: 4
hostname: ***
name: Java HotSpot(TM) 64-Bit Server VM
osArch: amd64
osName: Windows 7
vendor: Oracle Corporation
version: 25.121-b13
Parameters(model -> 0): 0.081482
Parameters(model -> 1): 0.073783
Parameters(model -> 2): 0.069933
Parameters(model -> 3): 0.070254
Parameters(model -> 4): 0.065122

::Benchmark Range.protostuff::
cores: 4
hostname: ***
name: Java HotSpot(TM) 64-Bit Server VM
osArch: amd64
osName: Windows 7
vendor: Oracle Corporation
version: 25.121-b13
Parameters(model -> 0): 0.00385
Parameters(model -> 1): 0.003528
Parameters(model -> 2): 0.003529
Parameters(model -> 3): 0.003528
Parameters(model -> 4): 0.003528

  

报告给出了机器cpu核心数量,操作系统信息,局部代码运行时间。

通过对比发现protostuff比json的速度快20-30倍。

scalameter和scalacheck提供了scala风格的api,写起来顺手,不会感觉到去调用java的api时候的别扭。如果有其他更好的工具欢迎留言。

posted on 2018-10-09 14:46  skyer1992  阅读(644)  评论(0编辑  收藏  举报

导航