【问题标题】:Testing class who extends another class(PHPUNIT)扩展另一个类的测试类(PHPUNIT)
【发布时间】:2021-03-14 12:58:15
【问题描述】:

我在 phpUnit 中测试时遇到问题,我有 "class class_A extends Class_B"

我不知道如何测试,我试图像这样模拟 b 类

$this-> mock = $this-> getmock('class_A',array('Class_B'));

但是当我运行测试时,测试失败并返回这个

class_b::__construct() 缺少参数 1,

有人知道我该怎么做吗?

(对不起,如果我的英语很烂!!)

【问题讨论】:

  • 我需要测试 class_A,但 class_b 询问他的论点,我不知道如何模拟 class_b 或我必须为 class_b 做些什么而不影响测试
  • 最后,在这种情况下我必须这样做: $mocking= new class_a($mock ,$mock_parameter_2 );为了模拟class_B。这样我就可以测试我的班级_A 谢谢大家!!

标签: php unit-testing phpunit


【解决方案1】:

我想这就是你要找的:

assertInstanceOf

(见于:https://stackoverflow.com/a/7680164/3454966

编辑:如果您只想测试继承,请在构造函数中使用任何有效参数。

【讨论】:

    【解决方案2】:

    您可以按照docs 中的说明禁用构造函数:

    $stub = $this->getMockBuilder('Class_A')
                     ->disableOriginalConstructor()
                     ->getMock();
    

    【讨论】:

    • 我必须测试 class_A ,但是当我尝试测试它时,b 类要求他的构造函数的参数,我想模拟 class_b 因为我不需要只测试方法class_A 的(我也是 phpunit 的新手)
    【解决方案3】:

    我测试了类继承是否正确,父函数是否存在。

    protected $TestObject;
    
    protected function setUp()
    {
        $this->TestObject = new MyLib\Class_B;      // Namespaces being used?
    }
    
    public function testClassInstance()
    {
        $this->assertInstanceOf('MyLib\Class_A', $this->TestObject);
        $this->assertInstanceOf('MyLib\Class_B', $this->TestObject);
    }
    
    // For Instance: These are from the Class A that was extended
    public function testClassAWorks()
    {
        $this->assertEquals('String', $this->TestObject->GetString(), 'Ensure the Class_A inherited function is returning String');
        $this->assertFalse($this->TestObject->IsFalseFunction());
    }
    
    // These are from the Class B
    public function testClassBWorks()
    {
        $this->assertEquals('Number', $this->TestObject->GetString2(), 'Ensure the Class_B function is returning Number');
        $this->assertTrue($this->TestObject->IsTrueFunction());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多