Symfony PHPunit测试-如何模拟服务



我只是想知道如何模拟Symfony中的服务。

这就是我到目前为止所得到的结果,但它并没有像预期的那样起作用。我希望NetballFeedService中的getVenuesData()方法在测试中转储模拟数据(我在命令中设置了DD(。但当我运行测试时,它会转储从NetballFeedService中提取的实时数据。

测试:

public function it_imports_venues(): void
{
$kernel = self::bootKernel();
$netballAPIMock = $this->createMock(NetballFeedService::class);
$netballAPIMock->method('getVenuesData')->willReturn([
800 => ['name' => 'Venue 1', 'location' => 'MEL'],
801 => ['name' => 'Venue 2', 'location' => 'ADE']
]);
$this->getContainer()->set('netballAPI', $netballAPIMock);
$container = $kernel->getContainer();
$container->set('netballAPI', $netballAPIMock);
$application = new Application($kernel);
$command = $application->find('app:feed:import-venues');
$commandTester = new CommandTester($command);
$commandTester->execute([]);
$commandTester->assertCommandIsSuccessful();
}

正在测试的命令:

protected static $defaultName = 'app:feed:import-venues';
public function __construct(
private readonly NetballFeedService $netballFeedService,
private readonly VenueService $venueService
)
{
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$data = $this->netballFeedService->getVenuesData();
dd($data);
$this->venueService->updateVenuesDataFromFeed($data);
return 0;
}

类方法应返回模拟数据:

public function getVenuesData(): array
{
$response = $this->client->request('GET', self::FIXTURES_URL);
$rawData = json_decode($response->getBody()->getContents(), true);
$rounds = $rawData['data']['results'];
$parsedVenuesData = [];
foreach ($rounds as $round) {
foreach ($round['matches'] as $matches) {
$venueId = $matches['venueId'];
if (array_key_exists($venueId, $matches)) {
continue;
}
$parsedVenuesData[$matches['venueId']] = [
'name' => $matches['venueName'],
'location' => $matches['venueLocation']
];
}
}
ksort($parsedVenuesData);
return $parsedVenuesData;
}

我正试图在Symfony中复制我的Laravel测试代码:

/** @test */
public function it_imports_venues()
{
$this->withExceptionHandling();
$this->instance(
NetballAPI::class,
Mockery::mock(NetballAPI::class, function (MockInterface $mock) {
$mock->shouldReceive('getVenuesData')->once()
->andReturn([
800 => [
'name' => 'Venue 1',
'location' => 'MEL'
],
801 => [
'name' => 'Venue 2',
'location' => 'ADE'
],
]);
})
);
$this->artisan('import:venues');
$this->assertDatabaseHas('venues', [
'id' => 800,
'name' => 'Venue 1',
'location' => 'MEL'
]);
$this->assertDatabaseHas('venues', [
'id' => 801,
'name' => 'Venue 2',
'location' => 'ADE'
]);

services_test.yml

services:
_defaults:
public: true
AppServiceNetballFeedService:
public: true
alias: netballAPI

只是想知道如何在测试实例中模拟NetballFeedService类?提前谢谢。

我错误地配置了service_test.yaml。应该是:

services:
AppServiceNetballFeedService:
public: true
app.netballFeedService:
alias: AppServiceNetballFeedService
public: true

此外,我还不太习惯使用YAML文件进行配置。它的可读性不太好,尤其是与本例中的PHP文件相比。因此,我将尝试使用YAML&配置/路由等的PHP文件

最新更新