【问题标题】:Unable to add more than one function to Test Class in Laravel无法在 Laravel 的测试类中添加多个函数
【发布时间】:2018-05-19 16:13:47
【问题描述】:

我正在使用 Laravel 开发一个 Web 应用程序。我想对一些逻辑进行单元测试。所以我创建了一个单元测试类,如下所示。

class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }


}

我从终端运行单元测试,它正在工作。然后我添加了另一个测试功能。所以我的测试类会是这个样子。

class AcceptationTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testCountUpWhenDifferenceIsOverOneWeek()
    {
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-28-2017");
        $this->assertTrue($need_count_up);
    }

    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}

当我从终端运行测试时,它显示此错误。

我仔细检查了我的第二个函数,没有错误。为了确保我删除了第一个函数并单独运行第二个函数。所以我的测试类会是这个样子。

class AcceptationTest extends TestCase
{


    public function testNotCountUpIfDifferenceIsExactlySeven(){
        $acceptationRepo = new AcceptationRepo;
        //must count up on 5/12/2017
        $need_count_up = $acceptationRepo->shouldCountUpTwoDWeek("11-29-2017");
        $this->assertTrue(!$need_count_up);

    }
}

如您所见,测试类中只有一个函数,那就是新添加的函数。我再次从终端运行测试,现在它可以正常工作而不会引发任何错误。我发现问题在于添加了多个功能。但我需要这样做。我从终端读取了错误消息,它根本不处理单元测试。

我尝试添加这两个属性

protected $preserveGlobalState = FALSE;
protected $runTestInSeparateProcess = TRUE;

当我运行时,它给了我这个错误

【问题讨论】:

    标签: php laravel unit-testing phpunit


    【解决方案1】:

    一种选择是从代码中删除常量。在大多数使用常量的地方,您应该能够引用env 变量或config 变量。

    其他选项是使用这些标志来确保每个测试都有自己的进程:

    class AcceptationTest extends TestCase
    {
    
      protected $preserveGlobalState = FALSE;
      protected $runTestInSeparateProcess = TRUE;
    

    最后,您可以在定义常量的任何位置添加测试

    if (!defined('SITE_NAME')) define('SITE_NAME', 'foobar');
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 2014-06-18
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多