【问题标题】:I get this Error when trying to run a PhpUnit test on my Drupal project尝试在我的 Drupal 项目上运行 PhpUnit 测试时出现此错误
【发布时间】:2017-04-20 10:08:30
【问题描述】:

TypeError: 传递给 Drupal\views\Plugin\views\HandlerBase::__construct() 的参数 1 必须是数组 phpunit 类型

我的代码是:

use Drupal\views_simple_math_field\Plugin\views\field\SimpleMathField;

class BasicTest extends PHPUnit_Framework_TestCase
{
   public function test_proba()
   {
     $first = 25;
     $second = 5;
     $result = 13;
     $test = new SimpleMathField();
     $working = $test->plus($first,$second,$result);
     $this->assertEquals($result,$working);

 }
}

我认为错误在“ $test = new SimpleMathField(); 之内,因为当我像这样运行它时测试运行完美:

<?php

use Drupal\views_simple_math_field\Plugin\views\field\SimpleMathField;

class BasicTest extends PHPUnit_Framework_TestCase
{
   public function test_proba()
   {
     $first = 25;
     $second = 5;
     $result = 13;
    $this->assertTrue(True);

 }
}

【问题讨论】:

  • 你在测试一个名为 Basic 的类吗?
  • 我正在 SimpleMathFIeld 类中测试一个 plus() 函数,该类位于具有 Drupal\views_simple_math_field\Plugin\views\field\ 命名空间的外部 PHP 文件中。
  • 测试类的名称应以“Test”为后缀。所以应该是 SimpleMathFIeldTest 而不是 BasicTest。如果您不确定自己在做什么,我会推荐这个优秀的教程:jtreminio.com/2013/03/…

标签: php unit-testing testing drupal phpunit


【解决方案1】:

问题不在于您的测试,而在于您如何实例化该字段。通过一个抽象链,该类扩展了HandlerBase,链接的构造函数如下所示:

public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->is_handler = TRUE;
}

你可以试试这样的:

new SimpleMathField(array(), 'test_id', 'test_definition');

如果其中需要传递给 __construct 或由它们初始化的某些变量,您可能必须检查 plus() 方法。您还可以尝试一种称为部分模拟的方法,在该方法中禁用构造函数但将测试的方法保持在测试中:

$partiallyMockedField = $this->getMockBuilder(SimpleMathField::class)
    ->disableOriginalConstructor()
    ->setMethods([])
    ->getMock();

您可能需要在数组中添加一些需要模拟的方法。这些将替换为您在典型模拟中使用 expects()method() 指定的任何内容。

免责声明:我不确定您是否必须将空数组或显式 null 传递给 setMethods 才能完成这项工作,因为我自己很少使用部分模拟。您必须查看文档或自己尝试。

【讨论】:

  • 非常感谢我不能投票,但声誉仍然很低。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 2016-03-23
  • 2018-11-23
  • 2019-09-23
  • 2022-07-07
  • 1970-01-01
相关资源
最近更新 更多