I am working on a custom module that from a controller calls Elastic search and returns a search result. I am trying to write a simple Functional Php Unit test just to make sure the results are displaying correctly.
Here is a simplified version of my funtional php unit test code:
public function testSearchResulsShowUp() {
$account = $this->drupalCreateUser(['access content']);
$this->drupalLogin($account);
$this->drupalGet('/search/term1');
$this->assertResponse(200);
$this->assertText('Term 1');
}
Here is a simplified version of my controller:
/**
* Search controller.
*/
class SearchController extends ControllerBase {
public function getContent(search) {
$client = Client::getClient();
// Client connects to Elastic search and then returns
// a result.
...
...
// Will return Term 1
}
}
Here is a simplified version of my Client class:
/**
* Class Client.
*/
class Client {
/**
* Get client.
*/
public static function getClient() {
$cluster_id = \Drupal::state()->get('elasticsearch_connector_get_default_connector');
$elasticsearchCluster = \Drupal::entityManager()->getStorage('elasticsearch_cluster')->load($cluster_id);
$clientManager = \Drupal::service('elasticsearch_connector.client_manager');
$client = $clientManager->getClientForCluster($elasticsearchCluster);
return $client;
}
}
I would like to be able to somehow mock my getClient method so when it is called in the Controller or anywhere going forward it would call the mock instead of the original method. I know that if this was a true Unit test we would be able to do it but since it is a functional test I am not sure how to do it.
$this->drupalGet('/search/term1');
? – albertski Feb 8 '20 at 15:53new MyController($mocked_client, ...other deps from container));
. Then call your controller method that responds at that route. You can also set the container to a class for the mocked client (though I have not been able to get that to work). I tested a controller from a kernel test because I just needed to see what the controller returned. – Kevin Feb 8 '20 at 16:02new MyController($mocked_client)
and then run$this->drupalGet('/search/term1');
It will use my mocked version? – albertski Feb 8 '20 at 16:04