作者:旧瑾LA_364 | 来源:互联网 | 2023-01-30 12:18
ImwritingsomeunitteststotesttheAPIendpointsinmyLaravel5application,andalotofendp
I'm writing some unit tests to test the API endpoints in my Laravel 5 application, and a lot of endpoints require user authentication. Instead of having the same user account creation code in every test, I wanted to define a RegistersUsers
trait to use on the test classes, which will have a registerUser()
method.
我正在编写一些单元测试来测试Laravel 5应用程序中的API端点,并且许多端点需要用户身份验证。我没有在每个测试中使用相同的用户帐户创建代码,而是想要在测试类上定义一个RegistersUsers特性,它将具有registerUser()方法。
The directory structure of my tests
directory is like so:
我的tests目录的目录结构如下:
/tests
/Traits
RegistersUsers.php
TestCase.php
UserTest.php
I've namespaced TestCase.php
and UserTest.php
by adding this namespace declaration:
我通过添加此命名空间声明命名为TestCase.php和UserTest.php:
namespace MyappTests;
and I've namespaced RegistersUsers.php
like so:
我像这样命名为RegistersUsers.php:
namespace MyappTests\Traits;
My UserTest
looks like this, with the namespace and the use
declaration so that I can leverage RegistersUsers
.
我的UserTest看起来像这样,使用命名空间和使用声明,以便我可以利用RegistersUsers。
However, when I run the test, PHPUnit dies with the fatal error:
但是,当我运行测试时,PHPUnit死于致命错误:
Trait 'MyappTests\Traits\RegistersUsers' not found in /home/vagrant/demo-app-net/tests/UserTest.php on line 9
在第9行/home/vagrant/demo-app-net/tests/UserTest.php中找不到Trait'MyappTests \ Traits \ RegistersUsers'
As far as I can tell, my namespacing is correct and my trait should be found. I've been going around in circles with this and can't seem to figure it out.
据我所知,我的命名空间是正确的,应该找到我的特点。我一直在四处走动,似乎无法弄明白。
1 个解决方案
18
I'm guessing having the trait in the traits folder, the trait is no longer accounted for in your autoloader.
我猜测在traits文件夹中有这个特性,你的自动加载器中不再考虑这个特性。
In order to correct this, you should open up composer.json
, find the sectionfor autoload-dev
and change it to something like the following...
为了纠正这个问题,你应该打开composer.json,找到autoload-dev的部分并将其更改为如下所示...
"autoload-dev": {
"classmap": [
"tests/TestCase.php",
"tests/Traits/"
]
},
And that should add any traits you have in that folder to the autloader.
这应该将您在该文件夹中的任何特征添加到自动加载器。
Edit
Some additional ideas were brought up in the comments. If you are going to be maintaining proper folder/namespace structure, it would be a good idea to use psr-4 autoloading rather than maintaining the class map.
评论中提出了一些其他想法。如果您要维护正确的文件夹/命名空间结构,那么使用psr-4自动加载而不是维护类映射是个好主意。
"autoload-dev": {
"psr-4": {
"MyappTests\\": "tests/"
}
},
Also, rather than put logic in a trait to register a user for use with testing, when you extend TestCase
, it brings in a helper method for logging in as a certain user. You'd use it like so...
此外,在扩展TestCase时,不是将逻辑放在特征中来注册用户以进行测试,而是引入一个帮助方法以特定用户身份登录。你会这样使用它......
$user = User::find($id);
$this->be($user);