【发布时间】:2014-08-24 13:23:05
【问题描述】:
大家好,我有一个方法,它可以在特定情况下调用它自己,该方法的一个简短示例可以是:
class MyClass
{
protected $quantity;
public function add($quantity)
{
for($i = 0; $i < $quantity; $i++)
{
$newQuantity = $quantity - 1;
$this->setQuantity($newQuantity);
$this->add($this->quantity);
}
return $this->quantity;
}
public function setQuantity($quantity)
{
$this->quantity = $quantity;
}
}
如果我想为这种丑陋的方法编写一个测试(仅作为示例),我会这样做:
<?php
use Mockery as m;
class TestMyClass
{
public function teardown()
{
m::close();
}
public function test_add_method()
{
// Here come the problem because I need to mock that the method
// will be called, but if I mock it, I cannot call it for an
// assertion
$mockMyClass = m::mock('MyClass[setQuantity,add]');
$mockClass->shouldReceive('setQuantity')
->once()
->with(1)
->andReturn(null);
$result = $mockMyClass->add(1); // Here the problem
$this->assertEquals(0,$result);
}
}
但是我如何在代码上方编写 cmets,我无法正确模拟方法 add,因为我需要对其进行断言,但即使是这样,它也会再次被调用,我应该完成它的行为。
运行此单元测试的错误跟踪:
此模拟上不存在方法 Mockery_1_Mocks_My_Class::add() 对象
你如何实现这个小功能的测试?
【问题讨论】:
标签: unit-testing phpunit mockery