我试图为我在Drupal 8上写的自定义模块编写测试并且不断收到错误,此时我已经没有想法了。这是错误:
Error: Class 'Drupal\mypackage\Services\Config\MyClassServiceConfig' not found
PhpUnit类位于
之下 modules\custom\mypackage\tests\src\Unit\mypackageUserAuthTest
这是代码
class mypackageUserAuthTest extends UnitTestCase
{
protected $user;
protected $loginService;
public function setUp()
{
parent::setUp();
$this->loginService = new LoginService();
$this->user = [
'username' => 'xxx',
'password' => 'xxx',
'deviceId' => 'xxx',
'some-token' => 'xxx'
];
}
/** @test */
public function that_we_can_authenticate_a_user()
{
$IsUserLoggedIn = $this->loginService->login($this->user['username'], $this->user['password']);
$this->assertTrue($IsUserLoggedIn);
}
现在login
代码中的方法loginService
<?php
namespace Drupal\mypackage\Rest;
use GuzzleHttp\Exception\ClientException;
use Drupal\mypackage\Services\RestServiceFactory;
use Drupal\mypackage\Services\Config\MyClassServiceConfig;
class LoginService
{
public function login($username, $password)
{
$configs = new MyClassServiceConfig(null, "mobile", "v1");
$client = RestServiceFactory::create($configs);
try {
$response = $client->post('login', [
'json' => [
'username' => $username,
'password' => $password,
'deviceId' => 'onepiece',
],
]);
return json_decode($response->getBody(), true);
} catch (ClientException $exception) {
switch ($$exception->getResponse()->getStatusCode()) {
case 402: // This only applies to co members
throw new SubscriptionRequiredException();
case 403:
throw new BlockedAccountException();
case 409:
throw new DuplicateEmailException();
case 410:
throw new PasswordDoesNotExistException();
}
throw $exception;
}
}
}
pwd
结果在MyClassServiceConfig
类目录中
/var/www/cms/web/modules/custom/mypackage/src/Services/Config
但它似乎在$configs = new MyClassServiceConfig(null, "mobile", "v1");
行上失败了前面提到的错误:
1) Drupal\Tests\mypackage\Unit\mypackageUserAuthTest::that_we_can_authenticate_a_user
Error: Class 'Drupal\mypackage\Services\Config\MyClassServiceConfig' not found
顺便说一下,我正在使用drupal-project结构(https://github.com/drupal-composer/drupal-project)
答案 0 :(得分:0)
所以我花了好几天检查路径,但似乎文件没有加载,所以我最终将自定义模块添加到autload-dev
部分composer.json
。
"autoload": {
"classmap": [
"scripts/composer/ScriptHandler.php"
],
"files": ["load.environment.php"]
},
"autoload-dev": {
"psr-4": { "Drupal\\mypackage\\": "web/modules/custom/mypackage" }
},
现在至少它似乎加载了模块,因为我收到了与Drupal Container相关的其他错误
\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.
答案 1 :(得分:0)
这是一个古老的问题,同样的事情发生在我身上,因为我设法解决了以下问题:
在进行测试的课程的注释中,应进行以下类似操作:
@coversDefaultClass
批注必须与要测试的类的命名空间一起使用。
/**
* @coversDefaultClass \Drupal\my_module\MyModuleClassName
* @group my_module
*/
class MyModuleCaseTest extends UnitTestCase {
}
也许会为别人服务