dongtong1226 2015-07-06 19:08
浏览 59
已采纳

Laravel 5单元测试中未发现特征

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.

The directory structure of my tests directory is like so:

/tests
    /Traits
        RegistersUsers.php
    TestCase.php
    UserTest.php

I've namespaced TestCase.php and UserTest.php by adding this namespace declaration:

namespace MyappTests;

and I've namespaced RegistersUsers.php like so:

namespace MyappTests\Traits;

My UserTest looks like this, with the namespace and the use declaration so that I can leverage RegistersUsers.

<?php

namespace MyappTests;

use MyappTests\Traits\RegistersUsers;

class UserTest extends TestCase
{
    use RegistersUsers;

    // ... rest of the class

However, when I run the test, PHPUnit dies with the fatal error:

Trait 'MyappTests\Traits\RegistersUsers' not found in /home/vagrant/demo-app-net/tests/UserTest.php on line 9

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条回答 默认 最新

  • douzhuiqing1151 2015-07-06 19:20
    关注

    I'm guessing having the trait in the traits folder, the trait is no longer accounted for in your autoloader.

    In order to correct this, you should open up composer.json, find the sectionfor autoload-dev and change it to something like the following...

    "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.

    "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...

    $user = User::find($id);
    $this->be($user);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计