16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mockeryのクラス指定の考え方

Posted at

https://github.com/mockery/mockery
Mockery::mock()によるオブジェクト生成の考え方で、aliasとかoverloadとかプロキシとか、よくわからなかったのでメモ。ツッコミ募集!

#「クラス名」

  • 定義済みクラスの拡張として生成
  • 静的メソッドはいじれない
  • shouldDeferMissing()すると、既存メソッドを呼べる
  • m::mock('User')->shouldDeferMissing()m::mock('User')->makePartial()m::mock(new User)は同じような挙動(つまり既存メソッドを呼べる)。
class User{

	function fuga(){
		return 'hoge';
	}
	
	static function fuga(){
		return 'fuga';
	}

	function foo(){
		return 'foo';
	}
}

$obj = m::mock('User')->shouldDeferMissing();
$obj->shouldReceive('hoge')->andReturn('mocked_hoge');
$obj->shouldReceive('fuga')->andReturn('mocked_fuga');

$obj->hoge(); //mocked_hoge
Staff::fuga(); //fuga
$obj->foo(); //foo

#「alias:クラス名」

  • 未定義のクラスならなんでも、stdClassの拡張として生成(→つまりshouldDeferMissingはできない)
  • 追加したメソッドは、静的にも動的にも呼べる
  • 以後 new すると、空のmockが生成される
$obj = m::mock('alias:Bar');
$obj->shouldReceive('hoge')->andReturn('mocked_hoge');
$obj->shouldReceive('fuga')->andReturn('mocked_fuga');

$obj->hoge(); //mocked_hoge
Bar::hoge(); //mocked_hoge
Bar::fuga(); //mocked_fuga


$obj = new Bar;
$obj->hoge(); //error method not exists
$obj->foo(); //error method not exists

#「overload:クラス名」

  • 未定義のクラスならなんでも、stdClassの拡張として生成(→つまりshouldDeferMissingはできない)
  • 追加したメソッドは、静的にも動的にも呼べる
  • 以後 new すると、メソッド追加済みのモックが生成される
$obj = m::mock('overload:Bar');
$obj->shouldReceive('hoge')->andReturn('mocked_hoge');
$obj->shouldReceive('fuga')->andReturn('mocked_fuga');

$obj->hoge(); //mocked_hoge
Bar::hoge(); //mocked_hoge
Bar::fuga(); //mocked_fuga


$obj = new Bar;
$obj->hoge(); //mocked_hoge
$obj->fuga(); //mocked_fuga
16
16
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
16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?