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

评论 (写第一个评论)