【phpunit-每日一记】 assert && depends(依赖关系的使用)

in PHP with 0 comment

【phpunit-每日一记】 assert && depends(依赖关系的使用)assertEquals

assertEquals(float $expected, float $actual[, string $message = '', float $delta = 0])

eq: 用于校验两个变量是否相等,第一个为预期参数,第二个为实际参数。 assertEquals 当两种相等的断言成功。assertNotEquals 相反接受相同的参数

第二种用法

-检查预期与实际参数的差值,当大于 $delta的时候,断言失败,并抛出 $message 填写的错误

example :

namespace Surest\Weather\tests;

use PHPUnit\Framework\TestCase;

class EqualsTest extends TestCase
{
    public function testPush()
    {
        $stack = [];
    }

    public function testFailure()
    {
        $this->assertEquals('1',0);
    }

    public function testFailure1()
    {
        $this->assertEquals(10,7,'相差不能超过5',5);
    }
} 

assertEmpty && assertNotEmpty

assertEmpty(mixed $actual[, string $message = ''])

判断实际参数是否满足条件

assertTrue

assertTrue(bool $condition[, string $message = ''])

条件检查,检查$condition是否为真,否则断言失败抛出 $message 错误讯息

@depends 相关依赖关系

先看测试用例

...
class DependsTest extends \PHPUnit\Framework\TestCase
{
    public function testEmpty()
        {
            $stack = [];
            $this->assertEmpty($stack);
    
            return $stack;
        }
    
        /**
         * @depends testEmpty
         */
        public function testPush(array $stack)
        {
            array_push($stack, 'foo');
            $this->assertEquals('foo', $stack[count($stack)-1]);
            $this->assertNotEmpty($stack);
    
            return $stack;
        }
    
        /**
         * @depends testPush
         */
        public function testPop(array $stack)
        {
            $this->assertEquals('foo', array_pop($stack));
            $this->assertEmpty($stack);
        }
}

官方: 在上例中,第一个测试, testEmpty(),创建了一个新数组,并断言其为空。随后,此测试将此基境作为结果返回。第二个测试,testPush(),依赖于 testEmpty() ,并将所依赖的测试之结果作为参数传入。最后,testPop() 依赖于 testPush()。

public function testDe1()
 {
     $this->assertTrue(true);
     return 'first';
 }

 public function testDe2()
 {
     $this->assertTrue(true);
     return 'second';
 }

 /**
  * @depends testDe1
  * @depends testDe2
  */
 public function testRes()
 {
     # 判断是否相等
     $this->assertEquals([
         'first' , 'second' ,'zz'
     ],func_get_args());
 }
Comments are closed.