本文介绍了在phpunit中,__construct和setup之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,知道在测试类__construct中创建对象是一种好习惯,还是我们应该始终使用setup/teardown方法(或setUpBeforeClass/tearDownAfterClass方法)?

I am curious to know it is good practice to create object in test class __construct or we should always use setup/teardown approach ( or setUpBeforeClass/tearDownAfterClass approach)?

我知道每次测试都会调用事实集/拆解,所以如果我将objec创建代码放入其中,它将对您有好处吗?例如

I aware of the fact set/teardown gets called for each test so will it do any good if I put my objec creation code in it? e.g.

//mytestclass.php

//mytestclass.php

class MyTestClass extends PHPUnit_Framework_TestCase
{

    private $obj;

    protected function setUp()
    {
        $this->obj = new FooClass();

    }

   public testFooObj()
   {
     //assertions for $this->obj
   }


   ...

}

如果我在构造函数中像这样创建对象,可能是什么问题:

what could be the issues if I create object in constructor like this:

class MyTestClass extends PHPUnit_Framework_TestCase
    {

        private $obj;

        protected function __construct()
        {
            $this->obj = new FooClass();

        }

       public testFooObj()
       {
         //assertions for $this->obj
       }


       ...

    }

我尝试使用Google搜索以及PHPUnit文档无法获取有关的更多信息,请您帮我弄清楚哪一种是好的做法吗?

I tried googling around as well as PHPUnit documentation couldn't get much information about, Can you please help me to undetstand which one is good practice?

推荐答案

setUp()在运行每个测试之前都会被调用. __construct()发生在实例化您的类时.因此,如果您有多个测试,并且它们使用局部属性并对其进行了修改,则可以使用setUp()确保在运行每个测试之前它们是相同的. setUp()的相反是tearDown(),您可以在其中确保每次测试后清除测试数据.

setUp() gets called before each of your tests is ran. __construct() happens when your class is instantiated. So if you have multiple tests and they use local properties and modify them, using setUp() you can ensure that they are the same before each test is ran. The opposite of setUp() is tearDown() where you can ensure that test data gets cleaned up after each test.

这篇关于在phpunit中,__construct和setup之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:24