没有 return 任何东西的测试方法
Testing methods that don't return anything
我正在努力全神贯注于测试,而且我知道这比我想象的要容易。我的猜测是,我将不可避免地遇到麻烦,因为我先编写了代码,现在才进行测试,而不是进行测试驱动的开发过程。
我的问题是关于执行诸如包含文件之类的功能的函数。他们什么都不 return,但他们为整个剧本做了一些事情。
假设我有一个 class,其中包含一个文件:
<?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
),这很简单。
但是,根据是否包含文件,return include_file
函数上的布尔值是否可以接受?这不是一个多余的测试吗,因为在 运行 check_file_validity
函数时基本上发生了同样的事情?
我应该注意到包含文件的信息来自 URL,因此这里的文件不会在测试之外进行硬编码(除非我模拟 $_GET
参数) .
一般来说,我认为假设 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()
,您只需模拟 class,这样您就可以检查 include_file()
是否被调用,以及它是否得到了正确的参数。
至于include_file()
本身,就不用再测试了,因为它只包裹了include
.
我正在努力全神贯注于测试,而且我知道这比我想象的要容易。我的猜测是,我将不可避免地遇到麻烦,因为我先编写了代码,现在才进行测试,而不是进行测试驱动的开发过程。
我的问题是关于执行诸如包含文件之类的功能的函数。他们什么都不 return,但他们为整个剧本做了一些事情。
假设我有一个 class,其中包含一个文件:
<?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
),这很简单。
但是,根据是否包含文件,return include_file
函数上的布尔值是否可以接受?这不是一个多余的测试吗,因为在 运行 check_file_validity
函数时基本上发生了同样的事情?
我应该注意到包含文件的信息来自 URL,因此这里的文件不会在测试之外进行硬编码(除非我模拟 $_GET
参数) .
一般来说,我认为假设 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()
,您只需模拟 class,这样您就可以检查 include_file()
是否被调用,以及它是否得到了正确的参数。
至于include_file()
本身,就不用再测试了,因为它只包裹了include
.