短版本:对于单元测试,我需要一个不可读的文件来确保抛出正确的异常。显然,Git无法存储该不可读文件,所以我在测试时使用chmod 000
并使用git update-index --assume-unchanged
,这样Git就不会尝试存储不可读文件。但我无法签出不同的分支,但收到错误"您对以下文件的本地更改将被签出覆盖。"
有没有更好的测试方法,或者更好的使用Git的方法,让一切都能很好地运行?
长版本:在一个类中,我有一个读取文件的方法,以便将其内容导入数据库:
public function readFile($path) {
...
if(!is_readable($path))
throw new FileNotReadableException("The file $path is not readable");
...
}
我使用PHPUnit测试该方法,其中一个测试应该(间接)触发FileNotReadableException:
/**
* @expectedException Data'Exceptions'FileNotReadableException
*/
public function testFileNotReadableException() {
$file = '/_files/6504/58/6332_unreadable.xlsx';
@chmod(__DIR__ . $file, 0000);
$import = Import::find(58);
$import->importFile(array('ID'=>2, 'newFilename'=> $file), __DIR__);
}
测试后,git checkout other_branch
将中止:
error: Your local changes to the following files would be overwritten by checkout:
Data/Tests/_files/6504/58/6332_unreadable.xlsx
Please, commit your changes or stash them before you can switch branches.
Aborting
您有几个选项。
在测试中添加一个tearDown()
方法来重置文件权限,这样git就不会认为文件被修改了。然后,即使测试失败,文件也会被重置。
http://phpunit.de/manual/current/en/fixtures.html
public function tearDown() {
@chmod(__DIR__ . $file, 0755); //Whatever the old permissions were;
}
如果您使用的是PHP 5.3+,则可以使用名称间距并模拟is_readable
函数。在测试文件中,使用自己的函数覆盖is_readable
。您需要确保您的覆盖与正在测试的类在同一个命名空间中。
http://www.schmengler-se.de/-php-mocking-built-in-functions-like-time-in-unit-tests
在你的课堂上,你会这样做:
namespace SUT
class SUT {
public function readFile($path) {
...
if(!is_readable($path))
throw new FileNotReadableException("The file $path is not readable");
...
}
}
然后在测试中,你要做以下操作:
namespace SUT
function is_readable($filename) {
if (str_pos('unreadable') !== FALSE)) {
return false;
}
return true;
}
class SUTTest extends PHPUNIT_Framework_TestCase {
/**
* @expectedException Data'Exceptions'FileNotReadableException
*/
public function testFileNotReadableException() {
$file = '/_files/6504/58/6332_unreadable.xlsx';
$sut = new SUT();
$sut->readFile($file);
}
}
然后,您甚至不必将文件包括在您的repo中,也不必担心对其的权限。