I'm using Symfony 6.4.4, php 8.2.5
My class depends on other class, that sends http requests to microservice. For testing purposes I want to mock this class.
Code structure:
interface GatewayServiceInterface
{
public function sendRequest(): int;
}
class GatewayService implements GatewayServiceInterface
{
public function sendRequest(): int;
}
final readonly class TestedClass
{
public function __construct(
private GatewayServiceInterface $gatewayService,
private SomeClassA $someClassA,
private SomeClassB $someClassB
) {}
}
So now I want to test TestedClass. And I want it to use mock of GatewayServiceInterface.
Here is what I do
final class TestedClassTest extends WebTestCase
public function setUp(): void
{
parent::setUp();
$gatewayServiceMock = $this->createMock(GatewayServiceInterface::class);
$gatewayServiceMock->method->('sendRequest')->willReturn(200);
$testedClassWithMock = new TestedClass(
$gatewayServiceMock,
$this->container->get(SomeClassA::class),
$this->container->get(SomeClassB::class)
)
$this->container->set(
TestedClass::class,
$testedClassWithMock
);
/** Run some tests with TestedClass */
}
But when I run tests it still uses regular GatewayServiceInterface instead of MockObject.
Based on what I read on this site and symfony docs my code should work. What can I do wrong here?
Solution is here How to mock Symfony 2 service in a functional test?.
My mistake was that I was using Kernel's container instead of Client's container