测试类对象,然后调用相应的测试方法。
即测试的执行模式并不是
testObj = new ExampleTest(); testObj->testMethod1(); testObj->testMethod2();
而是
testObj1 = new ExampleTest(); testObj1->testMethod1(); testObj2 = new ExampleTest(); testObj2->testMethod2();
所以testMethod1()修改的属性状态无法传递给 testMethod2()使用。
PHPUnit则为我们提供了全面的hook接口:
public static function setUpBeforeClass()/tearDownAfterClass()//测试类构建/解构时调用 protected function setUp()/tearDown()//测试方法执行前/后调用 protected function assertPreConditions()/assertPostConditions()//断言前/后调用
当运行测试时,每个测试类大致就是如下的执行步骤
#测试类基境构建 setUpBeforeClass #new一个测试类对象 #第一个测试用例 setUp assertPreConditions assertPostConditions tearDown #new一个测试类对象 #第二个测试用例 setUp assertPreConditions assertPostConditions tearDown ... #测试类基境解构 tearDownAfterClass
所以我们可以在测试类构建时使用setUpBeforeClass创建一个 App\Example 对象作为测试类的静态成员变量(tearDownAfterClass主要用于一些资源清理,比如关闭文件,数据库连接),然后让每一个测试方法用例使用它:
<?php
namespace Tests;
use App\Example;
use PHPUnit\Framework\TestCase as BaseTestCase;
class ExampleTest extends BaseTestCase
{
// 类静态属性
private static $example;
public static function setUpBeforeClass()
{
self::$example = new Example();
}
public function testGetTrue()
{
// 类的静态属性更新
self::$example->setMsg("hello big_cat");
$result = self::$example->getTrue();
$this->assertTrue($result);
}
public function testGetFalse()
{
$result = self::$example->getFalse();
$this->assertFalse($result);
}
/**
* 依赖 testGetTrue 执行完毕
* @depends testGetTrue
* @return [type] [description]
*/
public function testGetMsg()
{
$result = self::$example->getMsg();
$this->assertEquals($result, "hello big_cat");
}
}
或者使用@depends注解来声明二者的执行顺序,并使用传递参数的方式来满足需求。
public function testMethod1()
{
$this->assertTrue(true);
return "hello";
}
/**
* @depends testMethod1
*/
public function testMethod2($str)
{
$this->assertEquals("hello", $str);
}
#执行模式大概如下
testObj1 = new Test;
$str = testObj1->testMethod1();
testObj2 = new Test;
testObj2->testMethod2($str);
内容版权声明:除非注明,否则皆为本站原创文章。
