【问题标题】:Object of class could not be converted to int类的对象无法转换为 int
【发布时间】:2019-05-02 14:32:21
【问题描述】:

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

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' => 'www@www.com',
        '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: 类 App\CustomerRepository 的对象无法转换为 int

你能帮帮我吗?

【问题讨论】:

  • Nitpick:这不是单元测试,而是集成测试,因为您不会模拟数据库的东西。

标签: php laravel unit-testing phpunit


【解决方案1】:

问题就在这里:

$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

您可以从数据库中获得一个对象 (instanceof stdClass),您不能简单地使用 + 1

整个事情大概是这样的

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

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

【讨论】:

  • 我试过但它说;stdClass类的对象无法转换为int
猜你喜欢
  • 2017-03-08
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多