为什么单元测试不更新db?

时间:2017-05-17 08:05:25

标签: laravel unit-testing laravel-5.4

我有一个方法可以将查询更新到db。如果请求是从用户界面发送的,那么一切都很好,但是如果来自单元测试的请求那么数据库中的记录没有更新。

mthod中的更新查询如下所示

          $game_periods_table = DB::table('game_periods')->where('id', $id);
          $current_update_array = [];

          if(array_key_exists('A', $count_throws)){
              $current_update_array['count_throws_a'] =  $count_throws['A'];
          }

          if(array_key_exists('B', $count_throws)){
              $current_update_array['count_throws_b'] =  $count_throws['B'];
          }

          $current_update_array['updated_at'] = date('Y-m-d H:i:s');

          $game_periods_table->update($current_update_array);

我的单元测试看起来像

protected $bgame;
protected $game_id = 95;

public function setUp(){
    parent::setUp();

    $game = new Game();
    $game = $game::find($this->game_id);

    if(is_null($game)){
        $this->fail('Game is not found!');
    }

    $this->bgame = new BGame($game);
}

public function testUpdateThrows(){
    $test_array = [
        'first_period_throws' => ['A' => 1, 'B' => 2],
        'second_period_throws' => ['A' => 3, 'B' => 4],
        'third_period_throws' => ['A' => 5, 'B' => 6],
        'ot_period_throws' => ['A' => 7, 'B' => 8],
    ];

    $this->assertTrue($this->bgame->updateThrows($test_array));
}`

测试结果还可以,但为什么我的记录不会更新?

从单元测试我使用测试数据库,但它与主数据库完全相同。

1 个答案:

答案 0 :(得分:0)

这有两个因素,第一个是您很可能使用单独的数据库进行测试。最重要的是,它看起来好像没有复制完整的测试文件,但它与use DatabaseTransactionsuse DatabaseMigrations有关。您可以阅读有关此here的更多信息,但基本概念是每次测试后,数据库事务将被回滚或迁移将全部重新运行。

  

一种选择是在每次测试后回滚数据库并进行迁移   在下次测试之前。 Laravel提供了一个简单的DatabaseMigrations   特质会自动为你处理。另一种选择是   将每个测试用例包装在数据库事务中。再一次,Laravel   提供方便的DatabaseTransactions特性   自动处理这个。

如果您想检查您是否使用单独的数据库进行测试,请转到phpunit.xml文件并查找db_connection,同时应如下所示:

<env name="DB_CONNECTION" value="mysql_testing"/>
相关问题