Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phpunit mock only one method in tested class - using Mockery

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());
    }
}
like image 997
Bolek Lolek Avatar asked Dec 12 '17 11:12

Bolek Lolek


People also ask

Which method is used to create a mock with PHPUnit?

PHPUnit provides methods that are used to automatically create objects that will replace the original object in our test. createMock($type) and getMockBuilder($type) methods are used to create mock object. The createMock method immediately returns a mock object of the specified type.

How do you use partial mock?

Partial mocks allow you to mock some of the methods of a class while keeping the rest intact. Thus, you keep your original object, not a mock object, and you are still able to write your test methods in isolation. Partial mocking can be performed on both static and instance calls. This is an elevated feature.

What is mocking a method?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.

What is PHP stub?

Stubs are normal, syntactically correct PHP files that contain annotated function, method, and class signatures, constant definitions, and so on. The coding assistance quality relies, apart from anything else, on the quality of these signatures and their PHPDoc @annotations provided in the stubs.


1 Answers

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

like image 169
Matteo Avatar answered Oct 20 '22 15:10

Matteo