单元测试 - 引用类的类变量


Unit Test - Referencing Class' Class' Variable

我正在为一个组件编写单元测试,并且无法伪造一些数据。我想知道是否可以引用另一个类的类中的变量?

设置示例:

Unit Test > Human > Sports > $this->option['duration']

我正在为我的 Human 类编写一个单元测试。Human 类调用 Sports 类,Sports 类引用自己的变量$this->option['duration']。我希望能够修改单元测试中$this->option['duration']的值。我想知道这是否可能?

试图在我的单元测试中创建一个模拟体育类,并在这个模拟类中设置我想要的$this->option['duration']值。但是我不知道如何将我的模拟体育课注入我的单元测试中。

class SportsMock extends Sports {
    $this->option[duration'] = 10;
}

对于这种模拟,你需要在你的类上有一个可能的依赖注入(DI)。

我的意思是,你的 Human 类不应该实例化 Sports,而是应该在构造函数中接受它,或者 - 更好的是 - 通过二传手方法。通过这种方式,您可以轻松创建一个模拟类,实例化它并将其注入到要测试的类的实例中。

class Human {
    /* ... */
    function setSports(Sports $sports) {
        $this->sports = $sports;
        return $this;
    }
    /* ... */ 
}

现在在您的测试中,您从体育扩展,以便它与二传手一起工作。

/* You can override any function in the original, to return some mock data */
class MockSports extends Sports {
    public $mock_data = array();
    function original_function() {
       return $mock_data['original_function'];
    }
}

虽然这可能适合您的需求,但测试库通常带有适当的模拟实用程序,这使得模拟更加方便,但这并没有改变这样一个事实,即 DI 使测试代码变得更加容易。

例:

function my_example_test() {
    $human = new Human();
    $mock_sports = new MockSports();
    $mock_sports->mock_data['original_function'] = 10;
    $human->setSports($mock_sports); // <-- here is the injection
    /* Below you can test if your human works like it should */
}