【问题标题】:Laravel testing function to see any changes in a databaseLaravel 测试功能以查看数据库中的任何更改
【发布时间】:2019-05-28 06:16:24
【问题描述】:

我需要一个函数,它会给我一个由一些 php 代码完成的表和记录的列表。该函数将从单元测试中执行。

我的想法是通过 Carbon 设置时间,执行一些 php 代码,然后运行此函数,该函数将获取数据库中所有表的列表,并为每个表运行选择以查找创建时的特定日期- at 和 updated-at 字段..

然后它返回在按表名分组的数据库中创建的记录集合。

或者,如果我很乐意获得数据库事务所做修改的列表。

我不知道这样的函数是否存在于 MySQL 级别或 Laravel 或 PHPUnit 中。

如果不存在,请帮我写。谢谢。

【问题讨论】:

    标签: mysql laravel-5 phpunit


    【解决方案1】:

    我现在就是这样解决的:

    功能

    function databaseChanges(Carbon $dateTime): array
    {
        $schema = config('database.connections.mysql.database');
        $tables = DB::select(
                "
                        SELECT `table_name`
                        FROM `information_schema`.`tables`
                        WHERE true
                            AND `table_type` = 'base table'
                            AND `table_schema`= ?
                    "
                , [$schema]
        );
        $result = [];
        foreach ($tables as $table) {
            try {
                $records = DB::table($table->table_name)
                    ->select('created_at', 'updated_at')
                    ->where('created_at', $dateTime)
                    ->orWhere('updated_at', $dateTime)
                    ->get();
                if ($records->count() > 0) {
                    $result[$table->table_name] = $records;
                }
            } catch (QueryException $ex) {
                //\Log::debug(get_class($ex));
            }
        }
    
        return $result;
    }
    

    单元测试

    class DataBaseTest extends TestCase
    {
    
        use DatabaseTransactions;
    
    
        public function test_data_base_changes(): void
        {
            $now = Carbon::now();
            Carbon::setTestNow($now); // stop the time
    
            $user = factory(User::class)->create();
    
            $changes = databaseChanges($now);
    
            $this->assertSame(['accounts', 'users'], array_keys($changes));
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2017-09-17
      • 2016-11-30
      • 2013-11-04
      • 2012-10-09
      • 1970-01-01
      • 2014-08-02
      相关资源
      最近更新 更多