Phpunit模拟测试类中只有一种方法 - 使用Mockery

时间:2017-12-12 11:23:55

标签: php unit-testing phpunit mockery

我从周开始学习phpunit。我不知道如何从测试类中仅模拟一个方法。 (这只是一个例子,所以我没有写名称空间)。也许你可以帮助我

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

并测试:

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());
    }
}

1 个答案:

答案 0 :(得分:4)

您可以使用partial mocks作为测试类的示例,您可以这样做:

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()); 
}

希望这个帮助