我想在我的存储库中为保存方法编写 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/