Answer the question
In order to leave comments, you need to log in
How to lock a service in DI in Symfony3.4 + Codeception when writing functional tests?
Good afternoon, there is a Symfony3.4 application that provides a REST API wrapper over a third-party service.
Working with a third-party service takes place in a class that is initialized in DI as a service:
AppBundle/Resources/config/services.yml
app.service.third_party_service:
class: AppBundle\Service\ThirdPartyService
arguments:
- "%third_party_service.url%"
- "@event_dispatcher"
/**
* Class ThirdPartyService
* @package AppBundle\Service
*/
class ThirdPartyService implements ThirdPartyInterface
{
/**
* @param string $username
* @param string $password
* @return bool
*/
public function login(string $username, string $password): bool
{
//some php code
}
/**
* @param string $email
* @param string $username
* @param string $password
* @return bool
*/
public function register(string $email, string $username, string $password): bool
{
//some php code
}
}
actor: FunctionalTester
modules:
enabled:
- Symfony:
app_path: 'app'
environment: 'test'
debug: true
part: SERVICES
- Doctrine2:
depends: Symfony
- REST:
depends: PhpBrowser
url: http://localhost/app_dev.php/api/v1
- \Helper\Functional
class AccountLoginCest
{
/**
* @param FunctionalTester $I
*/
public function testSuccessfulLogin(FunctionalTester $I)
{
$thirdPartyService = $I->grabService('app.service.third_party_service');
dump($thirdPartyService);
$I->sendPOST('/account/login', [
'login' => 'test',
'password' => 'test',
]);
$I->seeResponseCodeIs(HttpCode::OK);
}
}
Answer the question
In order to leave comments, you need to log in
It is not the service that needs to be replaced in a different environment, but the client.
You are testing the service, right?
<?php
namespace App\Http {
interface HttpClientInterface {}
class FakeHttpClient implements HttpClientInterface {}
class RealHttpClient implements HttpClientInterface {}
}
namespace App\Service {
class ThirdPartyService {
private $client;
public function __construct(\App\Http\HttpClientInterface $client) {
$this->client = $client;
}
}
}
?>
// prod
app.http_client:
class: App\Http\RealHttpClient
// test
app.http_client:
class: App\Http\FakeHttpClient
app.third_party_service:
class: App\Service\ThirdPartyService
arguments: [app.http_client]
// parameters.yml
app.third_party_service_class: App\Service\ThirdPartyService
// config_test.yml
app.third_party_service_class: App\Service\MockThirdPartyService
app.third_party_service:
class: "%app.third_party_service_class%"
class MockThirdPartyService extends ThirdPartyService {
public function foo($ignoredArguments) {
return true;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question