测试方法不返回任何内容

时间:2016-04-20 18:08:01

标签: php unit-testing phpunit

我正试图绕过测试,我知道这比我想象的要容易。我的猜测是,我将不可避免地遇到麻烦,因为我先编写代码并且刚刚进行测试,而不是测试驱动的开发过程。

我的问题是关于包含文件的功能。他们没有返回任何东西,但他们为整个剧本做了一些事情。

假设我有一个包含文件的类:

<?php 

class Includer {
    public function __construct() {
        $this->include_file("/var/www/index.html");
    }

    public function check_file_validity($file = "") {
        // Check to see if the file exists
        return true; // if exists
    }

    public function include_file($file = "") {
        if ($this->check_file_validity($file)) {
            include $file;
        }        
    }
}

我可以编写一个测试来声明文件存在(check_file_validity),这将是直截了当的。

但是,根据文件是否包含在include_file函数上返回布尔值是否可以接受?这不是一个冗余测试,因为在运行check_file_validity函数时基本上会发生同样的事情吗?

我应该注意,包含该文件的信息来自URL,因此这里的文件不会在测试之外进行硬编码(除非我模拟$_GET参数)。

1 个答案:

答案 0 :(得分:1)

通常,我认为假设PHP函数可以正常工作,并且不需要再次测试它们。相反,如果您想测试使用像include这样的函数的代码,那么将它包装起来可能是个好主意。所以代码看起来像这样:

<?php 

class Includer {
    public function __construct() {
        $this->include_file("/var/www/index.html");
    }

    public function check_file_validity($file = "") {
        // Check to see if the file exists
        return true; // if exists
    }

    public function include_file_if_exists($file = "") {
        if ($this->check_file_validity($file)) {
            $this->include_file($file);
        }        
    }

    public function include_file($file = "") {
        include $file;
    }
}

要测试include_file_if_exists(),您只需要模拟您的课程,这样您就可以检查是否调用了include_file(),以及是否获得了正确的参数。

对于include_file()本身,没有必要再对它进行测试,因为它只包装include

相关问题