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;
    }
  ));

评论 (写第一个评论)