PHP单元:创建使用

时间:2015-08-24 14:30:57

标签: php unit-testing phpunit

我正在为一个类编写PHP单元测试,这会产生一些curl请求。目前,每个测试都以我的类实例启动和登录指令开始,并以logout指令结束,例如

public function testSomeMethod(){
        $a = new myClass();
        $a->login();
        ....
        $a->logout();
        $this->assertTrue($smth);

我想创建一个公共对象$ a = new myClass(),在所有测试和所有测试后的logout方法之前调用login方法。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

根据PHPUnit文档here,您可以使用以下钩子方法:

  

每次测试都会运行一次setUp()和tearDown()模板方法   测试用例类的方法(以及新实例)。

另外

  

另外,还有setUpBeforeClass()和tearDownAfterClass()模板   在运行测试用例类的第一个测试之前调用方法   并且在分别运行测试用例类的最后一次测试之后。

在您的情况下,您可以将登录类定义为类成员并在setUpBeforeClass()方法中实例化(登录)并在tearDownAfterClass()

中进行注销

编辑:示例

考虑以下课程:

namespace Acme\DemoBundle\Service;


class MyService {


    public function login()
    {
        echo 'login called'.PHP_EOL;
    }

    public function logout()
    {
        echo 'logout called'.PHP_EOL;
    }

    public function doService($name)
    {
        echo $name.PHP_EOL;
        return $name;
    }
}

此测试用例:

use Acme\DemoBundle\Service\MyService;

class MyServiceTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var \Acme\DemoBundle\Service\MyService
     */
    protected static $client;

    public static function setUpBeforeClass()
    {
        self::$client = new MyService();
        self::$client->login();
    }

    public function testSomeMethod1()
    {
        $value = self::$client->doService("test1");
        $this->assertEquals("test1",$value);
    }

    public function testSomeMethod2()
    {
        $value = self::$client->doService("test2");
        $this->assertEquals("test2",$value);
    }

    public static function tearDownAfterClass()
    {
        self::$client->logout();
    }
}
  

转储以下输出:

     

登录名为.test1 .test2 logout,名为

     

时间:49毫秒,内存:6.00Mb

     

好(2次测试,2次断言)

希望这个帮助

答案 1 :(得分:0)

在类级别创建可重用/通用对象(在方法/函数中使用)@Matteo 的回答很有帮助,这是我的实现

不需要多重继承,或者 __construct() 构造函数,我花了很多时间(特别是来自 java 背景)

<?php

namespace Tests\Unit;

use Tests\TestCase;
use App\Services\HelperService;

class HelperServiceTest extends TestCase
{ 
    //Object that will be reused in function()'s of this HelperServiceTest class itself 
    protected static $HelperServiceObj;

   //this is the magic function
    public static function setUpBeforeClass()
    {
        self::$HelperServiceObj = new HelperService();
    }

    public function testOneHelperServiceToBeTrue()
    {
          $this->assertTrue(self::$HelperServiceObj->getValue());
    }

   public function testTwoHelperServiceToBeTrue()
    {
          $this->assertTrue(self::$HelperServiceObj->getValueTwo());
    }

}

setUpBeforeClass() 之类的魔术函数请参考官方文档 setUp() , setUpBeforeClass() , tearDown()

getValue() 类中 HelperServiceTest 函数的示例实现

<?php

namespace App\Services;

class HelperServiceTest
{
    function getValue(){
       return true;
    }

    function getValueTwo(){
       return true;
    }

}