简体   繁体   中英

Testing method with dependency and partial mock PhpUnit

i'm having some issue testing this easy method.

I check if a conversation exist with a method that belong to the class to test and then i remove that conversation with a method of the dependency.

The problem is that i cannot figure out how pass the dependency mocked after i tested the method remove because i already mocked the main class to test passing it the dependency for make sure that class is partial mocked.

This is my original method

    <?php

    /**
    * Remove the current user to be fan the current team
    *
    * @param $user_id (int) | current user id
    * @param $team_id (int) | current team id
    * @return bool | true | false
    */
    public function remove($user_id, $team_id) {

        try 
        {
            $fan = $this->check($user_id,$team_id);
            $this->fan->delete($fan->id); // this->fan is the dependency on my constructor
            return true;
        } 
        catch(FanNotFoundException $e) 
        {
            $this->errors = $e->message();
            return false;
        }

    }

My test that give me an error:

test_remove_fan_from_db Trying to get property of non-object

I guess because. i mocked partially the main class before that I tested the delete method of the dependency but i think there is no other way for mock partially the main Class "Team" for test the check method. But then i have to pass on that class the delete method tested. How?

<?php

public function test_remove_fan_from_db() {

        $mockInterface = m::mock('Core\Social\Fan\Repository\FanTeamRepositoryInterface');
        $mocked = m::mock('Core\Social\Fan\Entity\Team[check]',[$mockInterface]);

        $mocked->shouldReceive('check')
                        ->with(1,2)
                        ->once()
                        ->andReturn(true);

        $mockInterface->shouldReceive('delete')
                            ->with(1)
                            ->andReturn(true);

        $team = $mocked->remove(1,2);

        $this->assertTrue( $team );
    }

I did a beginner mistake i solved like that:

public function test_remove_fan_from_db() {

        $mockInterface = m::mock('Core\Social\Fan\Repository\FanTeamRepositoryInterface');

        $mockInterface->shouldReceive('delete')
                            ->once()
                            ->andReturn(true);

        $mocked = m::mock('Core\Social\Fan\Entity\Team[check]',[$mockInterface]);

        $mocked->shouldReceive('check')
                        ->with(1,2)
                        ->once()
                        ->andReturn(new Fans);

        $team = $mocked->remove(1,2);

        $this->assertTrue( $team );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM