LoginSignup
3
2

More than 3 years have passed since last update.

Mockeryですでに設定済みのshouldReceive()を上書きしたい場合のやり方

Posted at

setupで定義したMockメソッドの戻り値を変更しようとすると。。。

戻り値が変更されない!!

//...略

class ServiceTest extends TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->mockTestService = \Mockery::mock(TestService::class);
        $this->mockTestService->shouldReceive('validation')
            ->andReturn(true);
    }

    public function testValidation_trueが返却されること()
    {
        $this->assertTrue($this->mockTestService->validation()); // OK
    }

   /**
     * @expectedException ValidationException
     */
    public function testValidation_ValidationExceptionがスローされること()
    {
        $this->mockTestService->shouldReceive('validation')
            ->andThrow(ValidationException);

        $this->mockTestService->validation(); //NG 例外が発生しない
    }

}

どうすればあとから戻り値を定義しても動いてくれるか?

答えはちゃんと載っていました。
Mockery1.0 日本語訳
Github Mockery issue_401

//...略

class ServiceTest extends TestCase
{
    protected function setUp()
    {
        parent::setUp();

        $this->mockTestService = \Mockery::mock(TestService::class);
        $this->mockTestService->shouldReceive('validation')
            ->byDefault() //☆☆ポイント
            ->andReturn(true);
    }

    public function testValidation_trueが返却されること()
    {
        $this->assertTrue($this->mockTestService->validation()); // OK
    }

   /**
     * @expectedException ValidationException
     */
    public function testValidation_ValidationExceptionがスローされること()
    {
        $this->mockTestService->shouldReceive('validation')
            ->andThrow(ValidationException);

        $this->mockTestService->validation(); //OK
    }

}

これであとからでも戻り値を置き換えられるようになりました!

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2