使用 phpunit DB::table()->get() returns 数组而不是对象测试 Laravel 4.2

Testing Laravel 4.2 with phpunit DB::table()->get() returns arrays not an objects

我开始使用 phpunit 向遗留 Laravel 4.2 webapp 添加单元/功能测试,并且在使用 DB::table 时我看到了一个奇怪的错误。

这是一个非常简单的示例,测试命中了一个控制器方法,该方法调用 DB::table 然后结束并转储结果。

class ExternalFormTest extends TestCase {

    public function testGetExternalFormThankYouPage()
    {
        $response = $this->call('GET', 'test');

这是被命中的控制器方法。

public function getIndex()
{
    $results = DB::table('users')->get();
    dd($results);

这个returns数组的数组。

..array(12) {
  [0] =>
  array(74) {
    'id' =>
    int(1)
    [0] =>
    int(1)
    'account_number' =>
    int(1000)
    [1] =>
    int(1000)
    'account_admin' =>
    int(1)

但是如果我用浏览器点击它。

然后我得到一个对象数组...

array (size=12)
  0 => 
    object(stdClass)[1967]
      public 'id' => int 1
      public 'account_number' => int 1000
      public 'account_admin' => int 1
      public 'user_type' => int 1

这会导致整个应用程序出现大量错误。因为代码期望访问属性(即$individual_result->id)但结果是数组。我已经用内存中的 sqlite 和正常的 MySql 数据库尝试过这个。这是一个错误还是我遗漏了一些关于 Laravel returns 结果 and/or phpunit 如何工作的东西。

任何建议都会有所帮助。

这是我的 phpunit.xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
     backupStaticAttributes="false"
     bootstrap="bootstrap/autoload.php"
     colors="true"
     convertErrorsToExceptions="true"
     convertNoticesToExceptions="true"
     convertWarningsToExceptions="true"
     processIsolation="false"
     stopOnFailure="false"
     syntaxCheck="false"
>
    <testsuites>
        <testsuite name="Application Test Suite">
            <directory>./app/tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

无论您是在 phpunit 上使用还是在控制器内部使用都没有关系。行为(应该)是相同的。

您是否也在(我想)控制器上使用 ->get() 方法在浏览器上显示结果?

据我对 laravel 的了解,->get() 确实应该 return 结果作为数组。

抓取模式由config/database.php中的'fetch'键配置。这应该是 PDO::FETCH_CLASS。也许您已将其设置为 PDO::FETCH_ASSOC 用于测试环境?作为解决方法,您可以尝试直接在控制器中设置它,看看是否可以解决问题:

public function getIndex()
{
    DB::connection()->setFetchMode(PDO::FETCH_CLASS);
    $results = DB::table('users')->get();
    dd($results);
}

如果可行,那么只需弄清楚将其设置为 FETCH_ASSOC 的位置即可。