任何关于如何在 PHPUnit 中使用 setUp() 和 tearDown() 的真实例子? [英] Any real word example about how setUp() and tearDown() should be used in PHPUnit?

查看:21
本文介绍了任何关于如何在 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.

推荐答案

如果您单独执行每个测试方法,您的测试代码将共享很多行,这些行只是创建要测试的对象.此共享代码可以(但不应该)进入 setup 方法.

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.

创建要测试的对象所需执行的任何操作也会进入 setup 方法,例如创建注入测试对象的构造函数的模拟对象.

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());
}

这篇关于任何关于如何在 PHPUnit 中使用 setUp() 和 tearDown() 的真实例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆