关于如何在PHPUnit中使用setUp()和tearDown()的任何真实单词示例?

关于如何在PHPUnit中使用setUp()和tearDown()的任何真实单词示例?

问题描述:

在每次测试之前和之后都调用方法setUp()tearDown().但是,实际上,有什么真实的例子说明为什么我需要这个吗?

Methods setUp() and tearDown() are invoked before and after each test. But really, is there any real word example about why should I need this?

在检查其他人的测试时,我总是看到类似的东西:

Inspecting other people tests, I always see something like:

public function setUp()
{
    $this->testsub = new TestSubject();
}

public function tearDown()
{
    unset($this->testsub);
}

public function testSomething()
{
    $this->assertSame('foo', $this->testsub->getFoo());
}

当然,这种方式与旧的"局部变量方式几乎没有区别.

Of course, there is virtually no difference between this way and the "old" local variable way.

如果分别执行每个测试方法,则测试代码将共享很多行,这些行仅创建了要测试的对象.此共享代码可以(但不应该)进入设置方法.

If you do every test method individually, your test code will share a lot of lines that simply create the object to be tested. This shared code can (but not SHOULD) go into the setup method.

创建待测试对象所需做的所有事情也都进入设置方法,例如,创建注入到测试对象构造函数中的模拟对象.

Anything that needs to be done to create the object to be tested then also goes into the setup method, for example creating mock objects that are injected into the constructor of the tested object.

不需要删除任何内容,因为下一次对setup的调用将使用一组新的对象初始化类成员变量.

Nothing of this needs to be teared down because the next call to setup will initialize the class member variables with a new set of objects.

唯一需要拆卸的是测试是否永久遗留了某些东西,例如已创建的文件或数据库条目.编写执行此类操作的测试确实不是一个好主意,但是在某些时候,您不能再抽象了,而必须接触诸如硬盘驱动器,数据库或真实网络之类的东西.

The only thing that needs teardown is if your test leaves something behind permanently, like files that got created, or database entries. It really isn't a very good idea to write tests that do such things, but at some point you cannot abstract anymore and have to touch stuff like the harddrive, database or the real network.

因此,设置远远多于拆卸操作,如果此测试没有任何工作要做,我总是删除拆卸方法.

So there is a lot more setup than teardown needed, and I always delete the teardown method if there is no work to be done for this test.

关于模拟,我是这样工作的:

Regarding mocks, I work like this:

private $_mockedService;
private $_object;
protected function setUp()
{
    $this->_mockedService = $this->getMock('My_Service_Class');
    $this->_object = new Tested_Class($this->_mockService);
}

public function testStuff()
{
    $this->_mockedService->expects($this->any())->method('foo')->will($this->returnValue('bar'));
    $this->assertEquals('barbar', $this->_object->getStuffFromServiceAndDouble());
}