差不多一年后,我敢肯定你现在已经继续前进了。
你说:
弹性搜索不会索引创建的帖子。它应该被索引
为什么会被索引?当然,除非您有代码可以在您的 setUp() 中建立索引,或者您针对外部 ES 服务器进行测试并假设它始终可用并且包含您正在测试的确切数据。
另一个解决方案是模拟请求,因为 Elasticsearch 返回 JSON。我们需要做的就是模拟一个状态为 200 的 HTTP 请求,并返回 JSON。我们可以将这个 JSON 文件放在我们的 tests/ 目录中,它将包含 Elasticsearch 将返回的示例结果。
一个示例测试是这样的;
$handler = new MockHandler([
'status' => 200,
'transfer_stats' => [
'total_time' => 100
],
'body' => fopen(base_path('tests/Unit/mockelasticsearch.json'), 'r')
]);
$builder = ClientBuilder::create();
$builder->setHosts(['testing']);
$builder->setHandler($handler);
$client = $builder->build();
$response = $client->search([
'index' => 'my_index',
'type' => 'my_type',
'body' => [
[
'query' => [
'simple_query_string' => [
'query' => 'john',
'fields' => ['name']
]
]
]
]
]);
// Test against the "$response", i.e., $this->assertEquals(2 ...) etc.
然后在 JSON 文件中,您需要根据您的索引进行自定义;
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 121668,
"max_score": 1,
"hits": [
{
"_index": "test",
"_type": "test-type",
"_id": "1111",
"_score": 1,
"_source": {
"id": "1111",
"title": "Some Foo",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "2222",
"_score": 1,
"_source": {
"id": "2222",
"title": "Dolor Sit Amet",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "3333",
"_score": 1,
"_source": {
"id": "3333",
"title": "Consectetur Adipiscing Elit",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "4444",
"_score": 1,
"_source": {
"id": "4444",
"title": "Sed Do Eiusmod",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "5555",
"_score": 1,
"_source": {
"id": "5555",
"title": "Tempor Incididunt",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "6666",
"_score": 1,
"_source": {
"id": "6666",
"title": "Ut Labore Et Dolore",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "7777",
"_score": 1,
"_source": {
"id": "7777",
"title": "Magna Aliqua",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "8888",
"_score": 1,
"_source": {
"id": "8888",
"title": "Ut Enim Ad Minim",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "9999",
"_score": 1,
"_source": {
"id": "9999",
"title": "Veniam, Quis Nostrud",
"timestamp": "2017-08-02T15:45:22-05:00"
}
},
{
"_index": "test",
"_type": "test-type",
"_id": "0000",
"_score": 1,
"_source": {
"id": "0000",
"title": "Exercitation Ullamco Laboris",
"timestamp": "2017-08-02T15:45:22-05:00"
}
}
]
}
}