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

评论 (写第一个评论)