0
我正在学习php单元测试。我有问题;如何从方法设置属性值?这里是我的示例代码:php单元测试嘲讽从方法设置属性
class Variables
{
public $date;
public function setDate(\DateTime $date) {
$this->date = $date;
}
}
class Process
{
public function process(Variables $var) {
if ($var->date->getTimeStamp() > 0) {
return 'success';
}
return 'failed';
}
}
class ProcessTest extends PHPUnit_Framework_TestCase
{
public function testProcess()
{
$mock = \Mockery::mock('Variables');
$mock->date = new \DateTime();
$procy = new Process();
$actual = $procy->process($mock);
$this->assertEquals('success', $actual);
}
}
如上面的代码,我知道,我可以通过设置属性date
:
$mock->date = new \DateTime();
,因为它是公众。
如果财产date
是私人的或受保护的,该怎么办?如何从嘲弄中设置?我试图做这样的事情,但有一个错误。
$mock->shouldReceive('setDate')->once()->andSet('date', new \DateTime());
Sample类:
class Calculation {
protected $a;
protected $b;
protected $c;
public function __construct() {
;
}
public function setA($a) {
$this->a = $a;
}
public function setB($b) {
$this->b = $b;
}
public function call() {
$this->c = (int) $this->a + (int) $this->b;
}
public function getC() {
return $this->c;
}
}
我需要你的意见。
,但我的班级中没有方法'getDate'。如果我有,可能我只需要执行'$ mock-> shouldReceive('getDate') - >和返回($ date);' – kelaskakap
取决于您是否要声明'setDate()'是通过'$ date ',@kelaskakap。如果它对你的测试不重要,那么你不需要设置任何期望。 – localheinz
是的,我不需要从'setDate'方法中进行访问。我只想知道,如何在单元测试中使用Mockery从'setDate'方法设置属性'date'(如果它是私有的或受保护的)。因为我的班级中没有方法'getDate'。 – kelaskakap