d.k
d.k

Reputation: 157

Object of class could not be converted to int

I want to write phpunit test for save method at my repository. My repo code is:

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

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

I wrote this test:

public function testSaveNewUye()
{
    $request = array(
        'email' => '[email protected]',
        '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);
}

I got the error given below:

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

Can you help me?

Upvotes: 2

Views: 10691

Answers (1)

Daniel W.
Daniel W.

Reputation: 32290

Problem is here:

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

You are assigning and using variables not the same.

Try like this instead:

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

When doing $this->$repo-> PHP tries to convert the (object) $repo to a string $this->(object)-> which does not work.

Then you have a second error here:

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

From the database you get an object (instanceof stdClass) which you cannot simply + 1.

The whole thing is probably something like

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

(From the returned object, you want the property id.)

Upvotes: 4

Related Questions