imdhemy/es-testing-utils

Elasticsearch 测试工具

8.3.0 2022-10-07 09:51 UTC

This package is auto-updated.

Last update: 2024-09-07 15:18:23 UTC


README

Tests Latest Stable Version Total Downloads

单元测试不应依赖于正在运行的集群,而应使用模拟代替。更具体地说,应该模拟客户端响应。Elasticsearch 测试工具使您能够轻松地模拟 Elasticsearch 响应。

安装

您可以使用 composer

composer require --dev imdhemy/es-testing-utils

版本

使用方法

模拟器

Es 测试工具为您提供流畅的 Elasticsearch 模拟构建器,您可以使用如下方式:

use Imdhemy\EsUtils\EsMocker;

// Create ES client that returns the mock response
$client = EsMocker::mock(['tagline' => 'You know, for search.'])->build();

或者,您可以模拟一系列响应

use Imdhemy\EsUtils\EsMocker;

// The created client will return the `$info` response with the first request,
// and the `$search` response with the second request, and so on.
// Note: the `thenFail()` method mocks a request exception.
$client = EsMocker::mock($info)->then($index)->then($search)->thenFail($error)->build();

// Or you can directly fail the first request:
$client = EsMocker::fail($message)->build();

以下是在测试中使用 EsMocker 的完整示例

use Imdhemy\EsUtils\EsMocker;

$expected=['tagline' => 'You know, for search.'];
$client = EsMocker::mock($expected)->build();

$response = $client->info();
$body = (string) $response->getBody();

$this->assertEquals(json_encode($expected), $body);

Faker

Faker 类提供了一套方法,用于为您的测试生成随机数据。它提供了Faker库的所有方法,以及生成 Elasticsearch 数据的新方法。所有与 Elasticsearch 相关的方法都以 es 前缀开始。

use Imdhemy\EsUtils\Faker;

$faker = Faker::create();

$index = $faker->esIndexName(); // Returns a random index name
$createIndex = $faker->esCreateIndex(); // Returns create index response body

// Explore the Faker class to see all the available methods

致谢

许可

ES 测试工具是开源软件,许可协议为MIT 协议