【问题标题】:Testing that one class method calls another测试一个类方法调用另一个
【发布时间】:2015-06-24 18:06:33
【问题描述】:

假设我有以下课程。

class SomeClass {

    public function shortcutMethod($arg1) {
        return $this->method($arg1, 'something');
    }

    public function method($arg1, $arg2) {
        // some stuff
    }

}

所以shortcutMethod 是另一种方法的快捷方式。假设我想编写一个给定的测试,$arg1 shortcutMethod 将使用正确的参数正确调用 method

到目前为止,我认为我需要模拟该类以期望使用一些参数调用method,然后像这样在模拟对象上调用shortcutMethod (注意我使用的是 Mockery) em>。

$mock = m::mock("SomeClass");
$mock = $mock->shouldReceive('method')->times(1)->withArgs([
    'foo',
    'something'
]);

$mock->shortcutMethod('foo');

这会导致类似shortcutMethod() does not exist on this mock object 的异常。

我误解了 mocking 的用法吗?我知道对于依赖注入到类中的对象更有意义,但是在这种情况下呢?你会怎么做?也许更重要的是,这种测试没有用吗?如果有,为什么?

【问题讨论】:

    标签: unit-testing phpunit mockery


    【解决方案1】:

    您应该使用模拟来模拟被测类的依赖项,而不是被测类本身。毕竟,您正在尝试测试您班级的真实行为。

    你的例子有点基本。你将如何测试这样一个类将取决于你的method 函数的作用。如果它返回的值又由shortCutMethod 返回,那么我会说你应该只是断言shortCutMethod 的输出。 method 函数中的任何依赖项都应该被模拟(属于其他类的方法)。我对嘲弄不太熟悉,但我已经对你的示例进行了调整。

    class SomeClass {
    
       private $dependency;
    
       public function __construct($mockedObject) {
          $this->dependency = $mockedObject;
       }
    
       public function shortcutMethod($arg1) {
          return $this->method($arg1, 'something');
       }
    
       public function method($arg1, $arg2) {
          return $this->dependency->mockedMethod($arg1, $arg2);
       }
    
    }
    
    $mock = m::mock("mockedClass");
    
    $mock->shouldReceive('mockedMethod')->times(1)->withArgs([
       'foo',
       'something'
    ])->andReturn('returnedValue');
    
    $testCase = new SomeClass($mock);
    
    $this->assertEquals(
       'returnedValue',
       $testCase->shortcutMethod('foo')
    );
    

    话虽如此,可以部分模拟您的测试类,以便您可以测试shortCutMethod 函数的真实行为,但模拟出method 函数以断言它是使用预期参数调用的。看看部分模拟。

    http://docs.mockery.io/en/latest/reference/partial_mocks.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      相关资源
      最近更新 更多