我开始使用 phpunit 向遗留的 Laravel 4.2 webapp 添加单元/功能测试,并且在使用 DB::table
时我看到了一个奇怪的错误。
这是一个非常简单的示例,测试命中了一个调用 DB::table
的 Controller 方法,然后终止并转储结果。
class ExternalFormTest extends TestCase {
public function testGetExternalFormThankYouPage()
{
$response = $this->call('GET', 'test');
这是被命中的 Controller 方法。
public function getIndex()
{
$results = DB::table('users')->get();
dd($results);
这将返回一个数组。
..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 如何返回结果和/或 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>
最佳答案
获取模式由 config/database.php 中的 'fetch' 键配置。这应该是 PDO::FETCH_CLASS
。也许您已将其设置为 PDO::FETCH_ASSOC
用于测试环境?作为解决方法,您可以尝试直接在 Controller 中设置它,看看是否可以解决问题:
public function getIndex()
{
DB::connection()->setFetchMode(PDO::FETCH_CLASS);
$results = DB::table('users')->get();
dd($results);
}
如果这行得通,那么只需弄清楚将其设置为 FETCH_ASSOC
的位置即可。
关于php - 使用 phpunit DB::table()->get() 测试 Laravel 4.2 返回数组而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31063977/