我正在使用 PHP-DI 将类注入到构造函数中,如下所示
class StravaWebhookService extends ApplicationService
{
private ContainerInterface $container;
private UserService $userService;
private ActivityService $activityService;
public function __construct(
ContainerInterface $container,
UserService $userService,
ActivityService $activityService,
)
{
$this->container = $container;
$this->userService = $userService;
$this->activityService = $activityService;
}
public function activityCreate($activityId, $ownerId): void
{
$activity = $this->activityService->findByActivityId($activityId); // <--- want to mock this so I can return a predefined value in a test
}
}
现在我想知道是否可以用一个模拟替换我的构造函数中的一个参数,这样我就可以定义一个要返回的值,$this->activityService->findByActivityId($activityId);
而不是调用那个真正的类。
我试过了
- 使用 mockbuilder,问题是我必须模拟每个构造函数注入的类
$stravaWebhookService = $this->getMockBuilder(StravaWebhookService::class)
->setConstructorArgs([
$containerStub, //<----- have to mock or create this too
$activityServiceStub,
$stravaServiceStub, //<----- have to mock or create this too
])
->getMock();