【发布时间】:2021-02-28 18:40:54
【问题描述】:
您好,假设我想测试从 A 类运行的函数,我正在使用 Mockery 模拟外部依赖项:
class A {
protected myB;
public function __construct(B $param) {
$this->myB = $param;
}
protected function doStuff() {
return "done";
}
public function run() {
$this->doStuff();
$this->myB->doOtherStuff();
return "finished";
}
}
class B {
public function doOtherStuff() {
return "done";
}
}
所以我写了这样的测试:
public function testRun() {
$mockB = Mockery::mock('overload:B');
$mockB->shouldReceive('doOtherStuff')
->andReturn("not done");
$mockA = Mockery::mock(A::class)->makePartial()->shouldAllowMockingProtectedMethods();
$mockA->shouldReceive('doStuff')->andReturns("done");
$mockA->run();
}
这会引发这样的异常: 错误:在 null 上调用成员函数 doStuff()
我尝试了模拟在运行函数中调用的内部依赖项 B 的不同变体,但我总是以异常结束。
我在这里做错了什么?
【问题讨论】:
标签: unit-testing mocking phpunit mockery