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

评论 (写第一个评论)