为什么静态方法不可测试? [英] Why are static methods untestable?

查看:38
本文介绍了为什么静态方法不可测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么静态方法不可测试?请举例说明(如果可能,请使用 PHP).

Why are static methods untestable? Kindly exemplify (in PHP if possible).

推荐答案

静态方法本身并非不可测试,但如果被测试的对象调用静态方法,则测试不能介于两者之间"并使其调用存根方法代替.如果被测试的对象改为调用常规方法,则测试可以为它提供具有该方法的存根实现的替代对象.

Static methods themselves aren't untestable, but if the object being tested calls a static method then a test cannot "get in between" and make it call a stub method instead. If the object being tested instead calls a regular method, the test can give it an alternative object with a stub implementation of that method.

一般来说,刚性依赖项的可测试性较差,而依赖项注入(google it)使代码更易于测试.

In general, rigid dependencies are less testable while dependency injection (google it) makes code more testable.

例如,假设我们有一个静态方法 getCurrentUser() 被我们正在测试的类使用,如下

For instance, let's say we have a static method getCurrentUser() that is used by the class we are testing, as follows

class PostModel {
    //...
    public function getRecentPosts() {
        return $this->database->from('posts')
                ->where(array('user' => UserModel::getCurrentUser()))
                ->limit(10);
    }
}

现在 UserModel::getCurrentUser() 不能用存根方法替换.如果我们将其设为通过对象引用调用的常规方法,则可以在测试中传入替代存根对象.

Now UserModel::getCurrentUser() cannot be replaced with a stub method. If we make it a regular method that we call through an object reference instead, we can pass in an alternative stub object in our test.

class PostModel {
    private $userModel;
    public function __construct($userModel) { 
        $this->userModel = $userModel;
    }
    //...
    public function getRecentPosts() {
        return $this->database->from('posts')
                ->where(array('user' => $this->userModel->getCurrentUser()))
                ->limit(10);
    }
}

这篇关于为什么静态方法不可测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆