Reputation: 1339
I'm trying to wrap my head around testing, and I know it's easier than I think. My guess is that I'm going to inevitably have trouble because I wrote the code first and am just now doing tests, instead of having a test driven development process.
My question is about functions that do something like including files. They don't return anything, but they do something for the script as a whole.
Let's say I have a class that includes a file:
<?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;
}
}
}
I can write a test to assert that the file exists (check_file_validity
), and that would be straight forward.
However, would it be acceptable to return a boolean on the include_file
function based on whether or not the file was included? Wouldn't that be a redundant test since basically the same thing is happening when running the check_file_validity
function?
I should note that the information given to include the file is coming from the URL, so no files here would be hard coded outside of the tests (unless I mock the $_GET
parameters).
Upvotes: 2
Views: 214
Reputation: 3016
Generally, I think it's safe to assume PHP functions work, and there's no need to test them again. Instead, if you want to test the code that uses a function like include
, it might be a good idea to wrap around it. So the code could look like this:
<?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;
}
}
To test include_file_if_exists()
, you'd simply mock your class, so you can check whether include_file()
was called or not, and if it got the correct argument.
As for include_file()
itself, it's not necessary to test it anymore, as it only wraps include
.
Upvotes: 1