【发布时间】:2011-07-25 19:53:39
【问题描述】:
这与其说是一个问题,不如说是为了节省我刚刚在 PHPUnit 上浪费的时间。
我的问题是我的模拟对象在依赖测试中使用时没有返回预期值。似乎 PHPUnit 并没有在依赖测试之间保留相同的对象,即使语法使它看起来像这样。
有谁知道为什么 PHPUnit 会这样做?这是一个错误吗? PHPUnit 中的类似内容让其使用起来非常令人沮丧。
<?php
class PhpUnitTest
extends PHPUnit_Framework_TestCase
{
private $mock;
public function setUp()
{
$this->mock = $this->getMock('stdClass', array('getFoo'));
$this->mock->expects( $this->any() )
->method('getFoo')
->will( $this->returnValue( 'foo' ) );
}
public function testMockReturnValueTwice()
{
$this->assertEquals('foo', $this->mock->getFoo());
$this->assertEquals('foo', $this->mock->getFoo());
return $this->mock;
}
/**
* @depends testMockReturnValueTwice
*/
public function testMockReturnValueInDependentTest($mock)
{
/* I would expect this next line to work, but it doesn't! */
//$this->assertEquals('foo', $mock->getFoo());
/* Instead, the $mock parameter is not the same object as
* generated by the previous test! */
$this->assertNull( $mock->getFoo() );
}
}
【问题讨论】:
-
请添加命令行,当您遇到问题时如何调用 phpunit。 -- 你有什么理由让
$mock成为私人会员? -
AFAIK phpunit 在每次测试之前运行 setUp() 方法,以便重置 $this->mock 的值
-
我本以为你写下来的时候这会起作用,我认为
setUp()不会被调用@dependant 测试,所以我真的很惊讶这也失败了......那可能如果我有一个模拟传递给一个我用@depends 传递的类:) -
@itom99: 是的,我原以为 $this->mock 会被重置,但请仔细查看代码:在 testMockReturnValueInDependentTest() 中,mock 对象作为局部变量传入。
-
@hakre:你想知道我为什么将 $this->mock 设为私有,或者为什么我将它设为实例变量(而不是本地变量)吗?
标签: php mocking phpunit depends