测试也是开发过程中非常重要一环,本博客介绍Scala开发的主要目的是为了日后的Play应用开发做基础,开发环境采用IntelliJ IDEA 集成开发环境。因此使用IntelliJ 创建Play 应用时缺省使用的测试包(基于Spec2)

Play应用缺省在test目录下创建了两个测试类: 为ApplicationSpec和IntegrationSpec ,我们暂时不去管它们。以后在介绍Play开发时再说。
本系列博客介绍Spec2 测试(其它测试使用的模板还可以是scalatest, JUnit,TestNG),其测试的为通用的类(和Play特定的测试无关)。
Specs2 的测试规范分为两大类型:
- 单元测试规范: 这种测试规范和测试代码混合在一起,它通常用来测试单个类。
- 验收测试规范: 这种测试规范的为一个整体,与其测试代码分开,它通常用于熟悉集成或验收测试规范。
Specs2 测试为一种行为驱动测试方法,它的着重点在于使用可由人员的文字描述代码期望的一些行为,配合测试代码来验证所需要测试的代码符合期望的规范。
下面我们使用例子来说明一下两种风格的测试规范:
单元测试
单元测试规范派生于org.specs2.mutable.Specification ,使用should/in的格式。
1 | import org.specs 2 .mutable. _ |
3 | class HelloWorldUnitSpec extends Specification { |
5 | "HelloWorldUnit" should { |
6 | "contain 11 characters" in { |
7 | "Hello world" must have size( 11 ) |
9 | "start with 'Hello'" in { |
10 | "Hello world" must startWith( "Hello" ) |
12 | "end with 'world'" in { |
13 | "Hello world" must endWith( "world" ) |
验收测试规范
验收测试规范继承自org.specs2.Specification ,并且定义is 方法。
3 | class HelloWorldAcceptanceSpec extends Specification { def is = s 2 "" " |
5 | This is a specification to check the 'Hello world' string |
7 | The 'Hello world' string should |
8 | contain 11 characters $e1 |
13 | def e 1 = "Hello world" must have size( 11 ) |
14 | def e 2 = "Hello world" must startWith( "Hello" ) |
15 | def e 3 = "Hello world" must endWith( "world" ) |
运行测试
运行测试的方法有很多种,在Play环境下,可以使用 play test 来运行,在IntelliJ IDEA可以通过菜单

如果需要运行或调试单个测试用例,可以在测试用例点击右键,选择
