代码之家  ›  专栏  ›  技术社区  ›  Bolek Lolek

Phpunit只模拟测试类中的一个方法-使用mockry

  •  6
  • Bolek Lolek  · 技术社区  · 8 年前

    我从一周开始学法语。我不知道如何只模拟测试类中的一个方法。(这只是一个示例,所以我没有编写名称空间)。也许你能帮我

    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 回复  |  直到 8 年前
        1
  •  10
  •   Matteo    8 年前

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

    希望这有帮助

    推荐文章