I need to write APItests for a project(on Symfony) using Codeception. My API test is functional and using Symfony+REST modules. The Api method I'm testing uses an external service call. I just stub the response of the class method, but the stub does not work and the real class method is called. What do I need to fix in my test code or maybe I need to use another way?
Config codeception.yml
namespace: App\Tests
paths:
tests: tests
output: tests/_output
data: tests/_data
support: tests/_support
envs: tests/_envs
actor_suffix: Tester
bootstrap: codeception_bootstrap.php
extensions:
enabled:
- Codeception\Extension\RunFailed
params:
- .env.test
Config api.suite.yml
actor: ApiTester
modules:
enabled:
- Symfony:
app_path: 'src'
environment: 'test'
- Doctrine2:
depends: Symfony
cleanup: true
- REST:
url: /api/v1/
depends: Symfony
- \App\Tests\Helper\Api
Test code /tests/api/TestCest.php
namespace App\Tests\Api;
use App\Tests\ApiTester;
class TestApiCest extends BaseApiCest
{
public function addMetrics(ApiTester $I)
{
$this->mockB2bService($I);
$I->sendPost('/request', $body);
$I->seeResponseCodeIs(201);
}
}
Code for stubing
/tests/_support/Helper/ApiHelper.php
namespace App\Tests\Helper;
use Codeception\Module;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ApiHelper extends Module
{
public function getContainer(): ContainerInterface
{
/** @var Module\Symfony $symfony */
$symfony = $this->getModule('Symfony');
return $symfony->kernel->getContainer();
}
}
/api/BaseApiCest.php
namespace App\Tests\Api;
use App\Module\Service\B2BService\B2bResponse;
use App\Tests\ApiTester;
use App\Tests\Helper\ApiHelper;
use Codeception\Stub;
abstract class BaseApiCest
{
protected ApiHelper $apiHelper;
protected function _inject(ApiHelper $apiUser)
{
$this->apiHelper = $apiUser;
}
protected function mockB2bService(ApiTester $I): void
{
$container = $this->apiHelper->getContainer();
$serviceId = '\App\Module\Service\B2BService\B2bService';
$auth = Stub::make(
\App\Module\Service\B2BService\B2bService::class, [
'createSomeActive' => new B2bResponse(['success' => true, 'message' => '', 'code' => 200])
]);
$container->set($serviceId, $auth);
$I->persistPermanentService($serviceId);
}
Class I try to stub
/src/Module/Service/B2bService.php
class B2bService implements B2bServiceInterface
{
public function createSomeActive(SomeParams $params): B2bResponse
{
$response = $this->httpClient->post('/somerequest', $requestBody);
$decodedResponse = $this->jsonDecodeResponse($response);
return $decodedResponse;
//if sucsess then return ['success' => true, 'message' => '', 'code' => 200]
}
}
Aucun commentaire:
Enregistrer un commentaire