10.4 PHPUnit Doubles / Mocks / Stubs

龶龴龲龮龭龩龥龡龟龡龛龗龩龥龖龕龓龏龍龊龉龆龖龅龁齽齺齸龍龅龁齵龗齱齮齪齦齣齡龡齠齜齽齛齗齓齐齍龍齵龗齌齋齉齈龡龆龖齅齄齃Mock鼶鼲鼰龍鼮鼭鼩龶龴鼦鼤鼣鼢鼡龩龥龅龁鼰鼝齽

创建一个模拟

鼜鼙鼕鼔龆龖齅齄鼒龍齪鼐鼙鼎鼡鼕鼔鼍龖鼌龡龆龖鼊鼰龍鼈龛鼇龡鼆鼅鼂鼀黽黼黹黵黴 NULL齽

龊龉龍龉黬龶龴齵龗龆龖黨黥黡黟龍黝鼮黛黚 getMockBuilder() 麾 getMock() 鼂鼀麺麶龆龖齽

鼙齜麳麰龶龴鼡鼰龊麮麬麪麩鼌麥龍麣麢麡黚麩 getMock()齽

$query = $this->getMockBuilder('\Drupal\Core\Entity\Query\QueryInterface')
                       ->getMock();

禁用原始构造器

齛齗齅麞麛黚鼩麚麗麖鼌齽龆麒鼌鼅龆龖 __construct() 麈麖龍齵龗黽麆麂齽龶龴麀鹾龡鹽鹼鼣鼂麞龛黚鹻鼰齅麞鹺鹶鼙龡龩龥龍龉黬鹵麰龆龖鹱鹮龍鹭鹫鹨 disableOriginalConstructor() 鼂鼀麆麂鼇齽

$query_factory = $this->getMockBuilder('\Drupal\Core\Entity\Query\QueryFactory')
                                    ->disableOriginalConstructor()
                                    ->getMock();

抽象类

鹘麒齓齐齍龍鼙鹗黛黚龆龖鹖黟鼌齽鹔龥齍齸鹑齅麞龍龉黬鹐鹱龍黝鼮黛黚齍鹌龡鼂鼀鹈

$filter_plugin = $this->getMockBuilder('\Drupal\filter\Plugin\FilterBase')
                                ->getMockForAbstractClass();

模拟方法

鼜鼙齵龗鹇齅齄黵黴龩龥鹆鼒龍鼙黝鼮鹄鹁鸽鼌鼂鼀鼕鼔鸻黹齽

PHPUnit 鸴龍鼅鸱麗黝鸰龡鼂麞龲鸮鸬齽鸩龆齗鼐鸥龛鸩鸡齗龡鸞龲齽鸛齗龲鼀鸙龛鸕鸔齱齮鹈 龉黬麡黚黨黥黡黟龡 execute 鼂鼀龍鸐黵黴麖龓 [1 => 1] 齽麚麗麖齓齐齍龍鼦 $this->any() 鷵鹄鷴龏麬麪鷱鷯麩齽黡鼩鷮鷫鷧龡齅齄龍鼙黝鼮鷦鷢鷡龆麒鹆齽

$query = $this->getMockBuilder('\Drupal\Core\Entity\Query\QueryInterface')
                       ->getMock();

$query->expects($this->any())->method('execute')->willReturn([1 => 1]);

// or
$query->expects($this->any())->method('execute')->will($this->returnValue([1 => 1]));

返回映射(maps)的模拟方法

鷝龆龖龊鷙龍龶龴鹇齅齄鼂鼀黵黴麩龆龖鹆齽龶龴鷖黝鼮鷓鷏鷋鷊黵黴鷇鷄龡鹆齽

齛龖龊鷙黵黴龆龖鷁鶾麖龓齽麖龓麮龡鸩龆鶻龛麬麪鶸 get 鼂鼀龡鶴麖龍鹽麢龆鶻龛黵黴鹆齽龶龴鸕鸔齅齄黡黟鼜 $fieldDefinition->get(‘field_name’) 黽麡黚鼒黵黴鶟鶜鶙 test_field 齽鼌鶖龡龍鼜 $fieldDefinition->get(‘field_type’) 黽麡黚鼒龍黵黴 text 齽龉黬鼂鼀鼅鸛龖鷋鷊龍鼙黵黴龡鷁鶾鶐鶏龛齛鶍鹈 [ 'argument_one', 'argument_two', 'return_value']

$fieldDefinition = $this->getMockBuilder('\Drupal\Core\Field\BaseFieldDefinition')
                                    ->getMock();

$fieldDefinition->expects($this->any())->method('get')
  ->willReturnMap([
    ['field_name', 'test_field'],
    ['field_type', 'text'],
    ['fieldStorage', $fieldStorage],
  ]);

使用回调的模拟方法

龉黬鼙齵龗鶀鷫鷧鵾鵼龍鵹鵷鵶鵴黝齜鵲鵰龡鼌鵲鵬龍鼙黝鼮鵪鵩龆龖麈麖鷵鹄黵黴鹆齽鵧鼲鼰 PHP 鵥鵣鵟麥麈麖龍鵝鵛鼙黝鼮鼦麈麖鵙鵖鷵鹄鶴麖齽

$this->field = $this->getMockBuilder('\Drupal\Core\Field\FieldItemList')
                              ->disableOriginalConstructor()
                              ->getMock();

$this->field->expects($this->any())->method('getValue')
  // We use a function here so that the value is calculated at runtime.
  ->will($this->returnCallback(
    function() {
      return $this->testValue;
    }
  ));

评论 (写第一个评论)