单元测试 - 依赖声明

  • 作者:KK

  • 发表日期:2015.12.13


比如有两个测试方法,通过test组件里取得一个测试学生ID来找学生实例

/**
 * 测试模型能否正常找到学生
 */
public function testCreateInstance(){
	$student = Student::createStudent(8282);
	$this->assertInstanceOf('app\model\Student', $student);
}

/**
 * 测试添加金币是否会成功
 */
public function testBusiness(){
	$student = Student::createStudent(8282);
	$this->assertTrue($student->addCurrency(9));
}

接下来运行整个测试用例,但是testCreateInstance方法里如果createStudent后返回的模型并不是app\model\Student的实例,那么根本就没必要运行testBusiness,但测试框架会都运行,因为它不知道依赖关系.

那么告诉测试框架你的依赖关系,办法就是用phpdoc规范,@depends然后空格,写上你依赖的方法

/**
 * 测试模型能否正常找到学生
 */
public function testCreateInstance(){
	$student = Student::createStudent(8282);
	$this->assertInstanceOf('app\model\Student', $student);
}

/**
 * (↓↓↓↓↓注意下面↓↓↓↓↓)测试添加金币是否会成功
 * @depends testCreateInstance
 */
public function testBusiness(){
	$student = Student::createStudent(8282);
	$this->assertTrue($student->addCurrency(9));
}

这样测试框架在运行这个之前就会运行依赖的方法看看是否成功,成功才会运行这个 如果依赖多个测试方法,就要多行@depends,比如

/**
 * (↓↓↓↓↓注意下面↓↓↓↓↓)多个depends声明
 * @depends testCreateInstance
 * @depends testGetXXX
 */
public function testBusiness(){
	$student = Student::createStudent(8282);
	$this->assertTrue($student->addCurrency(9));
}
  • *PS:

    依赖关系只会在运行整个测试用例的时候生效,如果你单独运行testBusiness这个测试方法,是不会先运行testCreateFindInstance的

    默认情况下,运行整个测试用例时,A方法测试失败,B和C方法依然会被运行,但如果B和C的运行前提是A方法测试成功,那就要使用依赖,使A方法失败时B和C都被跳过,运行D,E,F这些方法去了

    另外还要注意的是,B和C方法虽然是依赖于A的成功,但不能依赖于A的数据,比如A方法将测试用例的私有属性数据从1改成2后,B和C都基于2开始进行计算是不行的,因为每次运行一个测试方法,测试用例都会被重新new一次,那么私有属性就变回默认值了