【问题标题】:Error when running multiple unit tests with a MySQL database connection in Laravel在 Laravel 中使用 MySQL 数据库连接运行多个单元测试时出错
【发布时间】:2015-01-02 22:40:40
【问题描述】:

我已经为我的几个 Laravel 模型构建了一些单元测试。这些是需要按特定顺序存储的项目的 Eloquent 模型,因此,具有向上、向下移动项目以及在删除项目时对排序进行碎片整理的方法。为此,我需要连接到一个测试数据库(我通过 app/testing/database.php 完成)并添加一些虚拟数据,然后才能测试这些方法。

这是我的 TestCase.php

<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

    /**
     * Creates the application.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

    public function prepareDatabaseForTests()
    {
            Artisan::call('migrate');
            Artisan::call('migrate:refresh');
            Artisan::call('db:seed');

            Mail::pretend(true);
    }
}

然后,运行我的第一个单元测试正常工作(SectionTest.php):

<?php

class SectionTest extends TestCase {

  public function setUp()
  {
    $this->prepareDatabaseForTests();
  }



  //Tests adding a new section
  public function testAddSection()
  {
    $this->assertTrue(true);
  }

}

当我添加第二组测试时,我得到了错误

致命错误:“Artisan”类未在 /home/vagrant/Sites/mysite/app/tests/TestCase.php 在第 26 行

这是我的第二个测试文件(CourseTest.php)的示例:

<?php

class CourseTest extends TestCase {

    public function setUp()
    {
        $this->prepareDatabaseForTests();

    }


  //Tests adding a new course
  public function testAddCourse()
  {
    $this->assertTrue(true);
  }
}

当我删除第二个测试文件(CourseTest.php)时,phpunit 测试工作正常。我尝试运行composer update 以确保自动加载已刷新,但仍然没有运气。谁能说明为什么会发生这种情况?

【问题讨论】:

  • 我也遇到了错误,包括 Facade 也不起作用

标签: unit-testing laravel phpunit


【解决方案1】:

您的迁移和重置订单无效。试试这个。

public function setUp()
{
    Artisan::call('migrate');
    Artisan::call('db:seed');
}

public function teardown()
{
    Artisan::call('migrate:reset');
}

查看this 示例。

注意:在进行单元测试时触摸数据库不是一个好习惯。我建议在你的单元测试中使用模拟。

【讨论】:

  • 我同意你关于数据库和模拟的观点,但是修复不起作用。几乎就像引导程序没有运行一样。有任何想法吗?非常感谢您的帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
  • 2020-10-12
  • 2021-02-02
  • 2018-08-09
  • 2012-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多