I have a test environment that runs the component tests for a product. I found that recently it was tough to test and successfully mock php's is_uploaded_file()
and move_uploaded_file()
but after a lot of searching and research I came upon PHPT. This really helped me a lot with testing those methods and expectations for file uploading. This is not a question about file uploading but how to integrate the phpt testcases into the basic phpunit testcases so that code coverage will run for the methods that are being tested as well. Here follows some code extracts:
files.php
class prFiles
{
// Instance methods here not needed for the purpose of this question
// ......
public function transfer(array $files, $target_directory,
$new_filename, $old_filename = '')
{
if ( (isset($files['file']['tmp_name']) === true)
&& (is_uploaded_file($files['file']['tmp_name']) === true) )
{
// Only check if old filename exists
if ( (file_exists($target_directory . '/' . $old_filename) === true)
&& (empty($old_filename) === false) )
{
unlink($target_directory . $old_filename);
}
$upload = move_uploaded_file(
$files['file']['tmp_name'],
$target_directory . '/' . $new_filename
);
if ( $upload === true )
{
return true;
}
else
{
return false;
}
}
return false;
}
}
file_upload_test.phpt
--TEST--
Test the prFiles::transfer() the actual testing of the file uploading.
--POST_RAW--
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryfywL8UCjFtqUBTQn
------WebKitFormBoundaryfywL8UCjFtqUBTQn
Content-Disposition: form-data; name="file"; filename="test.txt"
Content-Type: text/plain
This is some test text
------WebKitFormBoundaryfywL8UCjFtqUBTQn
Content-Disposition: form-data; name="submit"
Upload
------WebKitFormBoundaryfywL8UCjFtqUBTQn--
--FILE--
<?php
require_once dirname(__FILE__) . '/../../../src/lib/utilities/files.php';
$prFiles = prFiles::getInstance()->transfer(
$_FILES,
dirname(__FILE__) . '/../_data/',
'test.txt'
);
var_dump($prFiles);
?>
--EXPECT--
bool(true)
UtilitiesFilesTransferTest.php
class UtilitiesFilesTransferTest extends PHPUnit_Extensions_PhptTestCase
{
/**
* Constructs a new UtilitiesFilesTransferTest.
*
*/
public function __construct()
{
parent::__construct(dirname(__FILE__) . '/_phpt/file_upload_test.phpt');
}
}
So that all works. But I can't seem to get any coverage of the transfer method I am testing. Please can anyone help me?
EDIT: my coverage command looks like this :
@echo off
echo.
if not "%1"=="" goto location
goto default
:location
set EXEC=phpunit --coverage-html %1 TestSuite
goto execute
:default
set EXEC=phpunit --coverage-html c:\xampp\htdocs\workspace\coverage\project TestSuite
:execute
%EXEC%