1

I'm using PHP-DI to inject classes into the constructor as follows

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
    }
}

Now I'm wondering if it's possible to replace one of the arguments in my constructor with a mock, so that I can define a value to be returned by $this->activityService->findByActivityId($activityId); instead of calling that real class.

I've tried

  1. Use the mockbuilder, issue is I have to mock every constructor injected class
        $stravaWebhookService = $this->getMockBuilder(StravaWebhookService::class)
            ->setConstructorArgs([
                $containerStub, //<----- have to mock or create this too
                $activityServiceStub,
                $stravaServiceStub, //<----- have to mock or create this too
            ])
            ->getMock();
Miguel Stevens
  • 8,631
  • 18
  • 66
  • 125

0 Answers0