php - 类的对象无法转换为 int

标签 php laravel unit-testing phpunit

我想在我的存储库中为保存方法编写 phpunit 测试。我的 repo 代码是:

public function saveCustomer(Custom $custom)
{
    try
    {
        $custom->save();

        return array(
            'status' => true,
            'customerId' => $custom->getId()
        );
    }
    catch(\Exception $e)
    {
        return array(
            'status' => false,
            'customerId' => 0
        );
    }
 }

我写了这个测试:

public function testSaveNewUye()
{
    $request = array(
        'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5a2d2d2d1a2d2d2d74393537" rel="noreferrer noopener nofollow">[email protected]</a>',
        'phone' => '555 555 555',
        'password' => '34636'
    );
    $repo = new CustomerRepository();
    $result_actual = $this->$repo->saveCustomer($request);
    $result_expected = array(
        'status' => true,
        'customerId' => \DB::table('custom')->select('id')->orderBy('id', 'DESC')->first() + 1
    );
    self::assertEquals($result_expected, $result_actual);
}

我收到以下错误:

ErrorException: Object of class App\CustomerRepository could not be converted to int

你能帮我吗?

最佳答案

问题出在这里:

$repo = new CustomerRepository();
$result_actual = $this->$repo->saveCustomer($request);

您分配和使用的变量不一样。

尝试像这样:

$this->repo = new CustomerRepository();
//     ^------- assign to `$this`
$result_actual = $this->repo->saveCustomer($request);
//                      ^------- remove `$`

当执行$this->$repo->时,PHP尝试将(对象)$repo转换为字符串$this->(object) -> 这不起作用。

那么这里又出现了第二个错误:

\DB::table('custom')->select('id')->orderBy('id', 'DESC')->first() + 1

从数据库中,您将获得一个对象(stdClass 实例),您不能简单地+ 1

整个事情可能是这样的

\DB::table('custom')->select('id')->orderBy('id', 'DESC')->first()->id + 1

(从返回的对象中,您需要属性id。)

关于php - 类的对象无法转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53557477/

相关文章:

php - 值在数组中的准备语句

jquery - Laravel 5.8 require 函数在 app.js 中找不到

通过电子邮件验证电子邮件 :rfc, dns 的 Laravel faker 电子邮件

java - 测试休息服务

php - 直接将 html 代码保存到 CSV 文件,无需解释(Without Formatting)

php - 垃圾收集 Php

php - yII2:日期过滤器如何在 Gridview 中

php - Laravel 异步上传文件

.net - 是否有任何支持 .NET Compact Framework 的模拟库

perl - 如何在Perl中为简单的I/O子例程创建单元测试