【问题标题】:Phpunit mock only one method in tested class - using MockeryPhpunit 在测试类中仅模拟一种方法 - 使用 Mockery
【发布时间】:2018-05-26 01:39:53
【问题描述】:

我从一周开始就在学习 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());
    }
}

【问题讨论】:

    标签: php unit-testing phpunit mockery


    【解决方案1】:

    你可以使用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()); 
    }
    

    希望有帮助

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2014-08-24
      • 2020-05-13
      • 2017-08-16
      • 2015-04-09
      • 2019-03-13
      • 2017-02-27
      • 2016-01-28
      • 2016-09-17
      相关资源
      最近更新 更多