我有两个类,我想通过PHPUnit测试它。但我在嘲笑这些东西时做错了事。我想改变第一类调用的方法。
class One {
private $someVar = null;
private $abc = null;
public function Start() {
if ( null == $this->someVar) {
$abc = (bool)$this->Helper();
}
return $abc;
}
public function Helper() {
return new Two();
}
}
Class Two {
public function Check($whateverwhynot) {
return 1;
}
}
Class testOne extends PHPUnit_Framework_TestCase {
public function testStart() {
$mockedService = $this
->getMockBuilder(
'Two',
array('Check')
)
->getMock();
$mockedService
->expects($this->once())
->method('Check')
->with('13')
->will($this->returnValue(true));
$mock = $this
->getMockBuilder(
'One',
array('Helper'))
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('Helper')
->will($this->returnValue($mockedService));
$result = $mock->Start();
$this->assertFalse($result);
}
}结果是$result是NULL,而不是true
如果不使用assert行,则会收到一条错误消息:
F
Time: 0 seconds, Memory: 13.00Mb
There was 1 failure:
1) testOne::testStart
Expectation failed for method name is equal to <string:Check> when invoked 1 time(s).
Method was expected to be called 1 times, actually called 0 times.想法?
更新-环境:PHP5.4.3x,PHPUnit 3.7.19 --一件重要的事情:不能修改原始类(第一类和第二类)
发布于 2015-02-05 15:22:56
你搞错了你的模仿。您使用的是$this->getMockBuilder(),它只使用一个参数,即要模拟的类的名称。您似乎把它与需要多个的$this->getMock()混为一谈。
将测试更改为:
public function testStart() {
$mockedService = $this
->getMockBuilder('Two')
->setMethods(array('Check'))
->getMock();
$mockedService
->expects($this->once())
->method('Check')
->with('13')
->will($this->returnValue(true));
$mock = $this
->getMockBuilder('One')
->setMethods(array('Helper'))
->disableOriginalConstructor()
->getMock();
$mock
->expects($this->once())
->method('Helper')
->will($this->returnValue($mockedService));
$result = $mock->Start();
$this->assertFalse($result);
}这不是一个好的测试,因为我们需要模拟我们正在测试的类,但是您说您根本不能更改类。
发布于 2015-02-04 21:06:57
您可以使用来自乌萨饼的模拟。
课程:
class One
{
private $someVar = null;
private $abc = null;
private $two;
public function __construct(Two $two)
{
$this->two = $two;
}
public function Start()
{
if (null == $this->someVar) {
$abc = (bool)$this->Helper()->Check(1213);
}
return $abc;
}
public function Helper()
{
return $this->two;
}
}在构造函数注入对象Two中,您可以轻松地模拟这个对象。
class Two
{
public function Check($whateverwhynot)
{
return 1;
}
}和测试:
class OneTest extends PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function shouldCheckStart()
{
//given
$mock = Mock::create('\Two');
Mock::when($mock)->Check(Mock::any())->thenReturn(true);
$one = new One($mock);
//when
$start = $one->Start();
//then
$this->assertTrue($start);
}
}嘲弄的文档。
https://stackoverflow.com/questions/28326008
复制相似问题