例如我有课:
class ServiceOne{
public function testOne($name){
app(ServiceTwo::class, ['name' => $name])->testTwo();
}
}
class ServiceTwo{
__construct(private string $name){}
public function testTwo(){
//so domething with $this->name;
}
}
当我使用 phpunit 和嘲笑对 ServiceOne->testOne() 进行单元测试时,我有以下代码:
$mock = \Mockery::mock(ServiceTwo::class)
->shouldReceive('testTwo')
->once()
->getMock();
$this->app->bind(ServiceTwo::class, function () use ($mock) {
return $mock;
});
app(ServiceOne::class)->testOne('testing');
ServiceTwo 被模拟并且测试代码正在运行,但问题是无论 testOne() 方法内部是否是:
public function testOne($name){
app(ServiceTwo::class, ['name' => $name])->testTwo();
}
或
public function testOne($name){
app(ServiceTwo::class)->testTwo();
}
或
public function testOne($name){
app(ServiceTwo::class, ['name' => ''different])->testTwo();
}
我想断言 ServiceTwo 是在 ServiceOne->testOne() 内创建的,具有精确的参数字符串“testing”,有什么想法吗?
您的解决方案已经完成了大部分工作,但在将模拟绑定到服务容器时错过了将应用程序实例和参数拉入闭包的过程。
如果我们修改您现有的测试以将其引入,那么我们将可以访问这些属性来做出断言:
$mock = \Mockery::mock(ServiceTwo::class)
->shouldReceive('testTwo')
->once()
->getMock();
$this->app->bind(ServiceTwo::class, function (Application $app, array $params) use ($mock) {
$this->assertEquals('testing', $params['name']);
return $mock;
});
app(ServiceOne::class)->testOne('testing');