Phpunit mock only one method in tested class - using Mockery
Asked Answered
W

1

8

I'm learning phpunit since week. I don't have idea how to mock only one method from tested class. (it's example only so I didn't write namespaces). Maybe you can help me

class SomeService
{
    public function firstMethod()
    {
        return 'smth';
    }
    public function secondMethd()
    {
        return $this->firstMethod() . ' plus some text example';
    }
}

and test:

class SomeServiceUnitTest extends TestCase
{
    private $someService;

    public function setUp()
    {
        parent::setUp();
        $this->someService = new SomeService();
    }

    public function tearDown()
    {
        $this->someService = null;
        parent::tearDown();
    }

    public function test_secondMethod()
    {
        $mock = Mockery::mock('App\Services\SomeService');
        $mock->shouldReceive('firstMethod')->andReturn('rerg');
        exit($this->walletService->secondMethd());
    }
}
Whoops answered 12/12, 2017 at 11:23 Comment(0)
F
14

You can use a partial mocks, as example on your test class, you can do:

public function test_secondMethod()
{
    $mock = Mockery::mock('App\Services\SomeService')->makePartial();
    $mock->shouldReceive('firstMethod')->andReturn('rerg');
    $this->assertEquals('rerg plus some text example', $mock->secondMethd()); 
}

Hope this help

Flail answered 12/12, 2017 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.