【问题标题】:Mock or Stub a method in a php parent class模拟或存根 php 父类中的方法
【发布时间】:2021-02-09 00:54:00
【问题描述】:

我在phpunit中测试一个类,但我不是在嘲笑它,这个类是这样的:

class MyClass extends ParentClass
{
    public function doSomething($param)
    {
        //do some stuff
        $someValue = $this->anotherMethod(); //this method is defined in the parent class
        //do some other stuff with $someValue

        return $finalValue;
    }
}

在测试课中我是这样做的

public function testDoSomething($param)
{
    $myclass = new MyClass();
    //here I need to control the value of $someValue, as it affects the final value returned
    $res = $myClass->doSomething();

    $this->assertEqual('sonething', res);
}

所以我的问题是如何控制从 anotherMethod 方法返回的值?我更喜欢模拟它,所以它不会调用其中的其他方法

【问题讨论】:

  • 不是很清楚,但是你想重写父类方法来控制它们吗?
  • @nice_dev 这正是我的问题
  • 好吧,然后覆盖。如果您想控制输出,是什么阻止了您?也可以调用 parent:: another Method();我相信从父类获取输出,然后在覆盖的方法中调整输出。
  • 你能举个例子吗?谢谢。
  • 这有帮助吗? 3v4l.org/H3A0r

标签: php unit-testing phpunit php-7


【解决方案1】:

您可以部分模拟您的类并检测您不想测试的方法,如下例所示:

    public function testDoSomething()
    {
        /** @var \App\Models\MyClass $classUnderTest */
        $classUnderTest = $this->getMockBuilder(\App\Models\MyClass::class)
            ->onlyMethods(['anotherMethod'])
            ->getMock();

        $classUnderTest->expects($this->once())
            ->method('anotherMethod')
            ->willReturn('mocked-value');

        $this->assertEquals("from-test mocked-value", $classUnderTest->doSomething("from-test"));
    }

来源如下:

父类

class ParentClass
{

    public function anotherMethod() {
        return "parent-value";
    }
}

我的班级

class MyClass extends ParentClass
{
    public function doSomething($param)
    {
        //do some stuff
        $someValue = $this->anotherMethod(); //this method is defined in the parent class
        //do some other stuff with $someValue
        $finalValue = $param . ' '. $someValue;
        return $finalValue;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-08
    • 2013-02-24
    • 2010-11-03
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    • 2013-01-10
    • 2018-07-21
    相关资源
    最近更新 更多