No pude hacer que mi servicio simulado se usara desde el contenedor según los documentos, por lo que hice esto.
Realmente no necesito un BrowserTest per se, ya que solo quiero asegurarme de que el objeto Response contiene lo que debería. Creo una simulación de cliente e instalo el objeto del controlador yo mismo:
<?php
namespace Drupal\Tests\mymodule\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\mymodule\Controller\AuthorizeController;
use Drupal\node\Entity\Node;
use Drupal\file\Entity\File;
use Drupal\Core\File\FileSystem;
/**
* Tests the AuthorizeController controller.
*
* @group mymodule
*/
class AuthorizeControllerTest extends KernelTestBase {
/**
* @var array
*/
public static $modules = ['system', 'node', 'field', 'mymodule', 'file', 'mymodule_authtest', 'user', 'text']; /** * {@inheritdoc} */ public function setUp() { parent::setUp(); $this->installConfig(['node', 'user', 'mymodule_authtest', 'file']);
$this->installSchema('file', ['file_usage']); $this->installEntitySchema('user');
$this->installEntitySchema('node'); $this->installEntitySchema('file');
$module_path = drupal_get_path('module', 'mymodule_authtest'); $uri = $this->container->get('file_system')->copy("$module_path/fixtures/pdf/foo.pdf", 'public://foo.pdf', FileSystem::EXISTS_REPLACE);
$file = File::Create([ 'uri' => $uri,
]);
$file->save(); $node = Node::create(array(
'title' => t('Test Paper'),
'type' => 'working_paper',
'language' => 'en',
'field_id' => 'w12345',
'field_paper_working_paper' => $file->id(), )); $node->save();
}
/**
* Test different scenarios and responses from our controller.
*/
public function testControllerResponse() {
$node = $this->container->get('entity_type.manager')->getStorage('node')->load(1);
$client = $this->getMockClient(1, 3, 3);
$controller = $this->getAuthorizeController($client); $response = $controller->content($node);
$this->assertContains('You’ve used 3 of your 3 allowed downloads for the year.', $response->getContent());
$this->assertContains('Download Paper Anyway', $response->getContent());
$client = $this->getMockClient(1, 3, 1);
$controller = $this->getAuthorizeController($client); $response = $controller->content($node);
$this->assertContains('You’ve used 1 of your 3 allowed downloads for the year.', $response->getContent());
$this->assertContains('Download Paper Anyway', $response->getContent());
$client = $this->getMockClient(1, 2, 1);
$controller = $this->getAuthorizeController($client); $response = $controller->content($node);
$this->assertContains('You’ve used 1 of your 2 allowed downloads for the year.', $response->getContent());
$client = $this->getMockClient(0, 3, 3);
$controller = $this->getAuthorizeController($client); $response = $controller->content($node);
$this->assertNotContains('Download Paper Anyway', $response->getContent());
$this->assertContains('<a href="http://example.org?id=w12345" class="btn btn--primary btn--black">Purchase Paper for $5</a>', $response->getContent()); $this->assertContains('<a href="http://example.org?referer=http%3A//localhost/node/1" class="btn btn--primary btn--black">Have Access? Login to Account</a>', $response->getContent()); } /** * Return a mocked client. Allow changing of some values to influence the * controllers response object. */ protected function getMockClient(int $allow = 1, int $claims_max = 3, int $claims_used = 1) {
$client = $this->getMockBuilder('\Drupal\mymodule\Client\AuthorizeClient')
->disableOriginalConstructor()
->getMock();
$client->expects($this->any())
->method('request')
->with('w12345', FALSE)
->willReturn(
[
'allow' => $allow, 'claims_max' => $claims_max,
'claims_used' => $claims_used, 'failed_reason' => NULL, 'succeeded_reason' => NULL, 'subscriber_id' => 12345, 'subscriber_logo_url' => NULL, 'subscriber_name' => "Test", 'subscriber_type' => "SUBS", ] ); return $client;
}
/**
* Return a controller with a mocked client.
*/
protected function getAuthorizeController($client) { return new AuthorizeController($client, $this->container->get('renderer'), $this->container->get('entity_type.manager'), $this->container->get('request_stack'), $this->container->get('logger.factory'));
}
}
Esto parece un enfoque válido y los casos están funcionando y se ejecuta mucho más rápido que las pruebas del navegador. El mymodule_authtest
contiene un tipo de contenido con un par de archivos de configuración de campo y ejemplo de archivo PDF a utilizar en esta prueba.