CategoryAutocompleteTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Drupal\Tests\block\Unit;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\block\Controller\CategoryAutocompleteController;
  5. use Drupal\Tests\UnitTestCase;
  6. use Symfony\Component\HttpFoundation\Request;
  7. /**
  8. * @coversDefaultClass \Drupal\block\Controller\CategoryAutocompleteController
  9. * @group block
  10. */
  11. class CategoryAutocompleteTest extends UnitTestCase {
  12. /**
  13. * The autocomplete controller.
  14. *
  15. * @var \Drupal\block\Controller\CategoryAutocompleteController
  16. */
  17. protected $autocompleteController;
  18. protected function setUp() {
  19. $block_manager = $this->getMock('Drupal\Core\Block\BlockManagerInterface');
  20. $block_manager->expects($this->any())
  21. ->method('getCategories')
  22. ->will($this->returnValue(['Comment', 'Node', 'None & Such', 'User']));
  23. $this->autocompleteController = new CategoryAutocompleteController($block_manager);
  24. }
  25. /**
  26. * Tests the autocomplete method.
  27. *
  28. * @param string $string
  29. * The string entered into the autocomplete.
  30. * @param array $suggestions
  31. * The array of expected suggestions.
  32. *
  33. * @see \Drupal\block\Controller\CategoryAutocompleteController::autocomplete()
  34. *
  35. * @dataProvider providerTestAutocompleteSuggestions
  36. */
  37. public function testAutocompleteSuggestions($string, $suggestions) {
  38. $suggestions = array_map(function ($suggestion) {
  39. return ['value' => $suggestion, 'label' => Html::escape($suggestion)];
  40. }, $suggestions);
  41. $result = $this->autocompleteController->autocomplete(new Request(['q' => $string]));
  42. $this->assertSame($suggestions, json_decode($result->getContent(), TRUE));
  43. }
  44. /**
  45. * Data provider for testAutocompleteSuggestions().
  46. *
  47. * @return array
  48. */
  49. public function providerTestAutocompleteSuggestions() {
  50. $test_parameters = [];
  51. $test_parameters[] = [
  52. 'string' => 'Com',
  53. 'suggestions' => [
  54. 'Comment',
  55. ],
  56. ];
  57. $test_parameters[] = [
  58. 'string' => 'No',
  59. 'suggestions' => [
  60. 'Node',
  61. 'None & Such',
  62. ],
  63. ];
  64. $test_parameters[] = [
  65. 'string' => 'us',
  66. 'suggestions' => [
  67. 'User',
  68. ],
  69. ];
  70. $test_parameters[] = [
  71. 'string' => 'Banana',
  72. 'suggestions' => [],
  73. ];
  74. return $test_parameters;
  75. }
  76. }