I'm not very much knowledgeable about making PHPUnit and Drupal testing setup.
I am having problems regarding database calls.
I tried to setup phpunit test.
Inside my module/some_module
. I installed phpunit by running
composer require --dev phpunit/phpunit ^8
This is my module/some_module/composer.json
{
"autoload": {
"classmap": [
"src/"
]
},
"require-dev": {
"phpunit/phpunit": "^8"
}
}
This is my module/some_module/tests/SampleTest.php
<?php
use PHPUnit\Framework\TestCase;
use Drupal\nat\Controller\SampleController;
use Drupal\Core\Controller\ControllerBase;
final class SampleTest extends TestCase
{
public function testCanFilterData(): void
{
$this->getMockBuilder(ControllerBase::class)
->getMock();
$class = new ReflectionClass(SampleController::class);
$method = $class->getMethod('filterData');
$method->setAccessible(true);
$obj = new SampleController();
$args = [1, 2, 3];
$method->invokeArgs($obj, [$args]);
print_r($foo);
}
}
This is my module/some_module/src/Controller/SampleController.php
<?php
namespace Drupal\some_module\Controller;
use Drupal\Core\Controller\ControllerBase;
class SampleController extends ControllerBase {
public function index()
{
$ids = [1, 2, 3]
$data = [];
$data['some_data'] = $this->filterData($ids);
return [*
'#theme' => 'test_template',
'#data' => $data,
];
}
private function filterData($ids)
{
$connection = \Drupal::database();
$query = $connection->query("SELECT
id, name
FROM products
WHERE id IN (:ids[])",
[
':ids[]' => $ids,
]
);
return $query->fetchAll(\PDO::FETCH_ASSOC);
}
}
When I ran phpunit tests/NatTest.php
, I am getting this error:
1) NatTest::testCanBeCreatedFromValidEmailAddress
Error: Class 'Drupal' not found
So my question is how can I test this? I can't mock Drupal
because I actually want to execute a database query from Drupal. How can I do this?