php - 测试从同一个类调用另一个的静态方法
问题描述
我有一堂课:
namespace Models;
use Contracts\PathContract;
class Path implements PathContract
{
public static function getStorage(string $type): string
{
return storage_path(config('logs.storage_path', 'logs'))
.DIRECTORY_SEPARATOR
.$type;
}
public static function directoryExists(string $type): bool
{
var_dump(Path::getStorage($type)); // output: .../logs/vendor/orchestra/testbench-core/laravel/storage/logs/myCustomType
if (is_dir(self::getStorage($type))) {
return true;
}
return false;
}
}
我想测试directoryExists
静态方法:
public function testDirectoryExists(): void
{
$path = Mockery::mock(Path::class)->makePartial();
$path->shouldReceive('getStorage')
->once()
->andReturn('/var/log');
var_dump($path::getStorage('blah blah blah')); // output: /var/log
$this->assertTrue($path::directoryExists('myCustomType'));
}
从directoryExists
方法中,getStorage
方法不返回模拟值,而是返回真实值。有任何想法吗 ?
如何测试从同一类调用另一个的静态方法?
解决方案
不不不。您必须模拟依赖项,而不是测试代码。静态功能是不好的测试设计。
如果函数不是静态的,您可以使用Filesystem
和模拟它们。
在这种情况下,最好的方法是mock
使用temp
.
public function testDirectoryExists(): void
{
//prepare
$temp = sys_get_temp_dir();
$logsPath = 'logs';
$logsDir = $temp.DIRECTORY_SEPARATOR.$logsPath;
$type = 'someType';
mkdir($logsDir);
//mock
$this->app->useStoragePath($temp);
config()->set('logs.storage_path', $logsPath);
//assert not created
$this->assertFalse(Path::directoryExists($type));
//assert created
mkdir($logsDir.DIRECTORY_SEPARATOR.$type);
$this->assertTrue(Path::directoryExists($type));
}
更新
或者,如果你使用 Laravel,你可以使用File
外观:
public static function directoryExists(string $type): bool
{
return File::isDirectory(self::getStorage($type));
}
public function testDirectoryExists(): void
{
$type = 'myType';
$expectedDir = '/logs/vendor/orchestra/testbench-core/laravel/storage/logs/'.$type;
$mock = Mockery::mock(\Illuminate\Filesystem\Filesystem::class);
$mock->shouldReceive('isDirectory')
->with($expectedDir)
->andReturn(true);
$this->app->instance(\Illuminate\Filesystem\Filesystem::class, $mock);
$this->assertTrue(Path::directoryExists($type));
}
推荐阅读
- django - 带有 slug 标记的路径表达式,而不是在 django 中使用 url
- node.js - nodejs中的fineOne对象mongodb返回奇怪的对象
- ios - 如何在 B2C 登录时禁用 SFSafariViewController 调用上的登录弹出窗口
- oracle - 如何创建具有唯一名称的表,然后将另一个表中的数据插入到该表中,最好使用单个触发器
- canvas - 列表视图中带有刻度/平移的画布。如何禁用滚动
- node.js - Nodejs区分http请求;具有相同公共 IP 的多个设备
- python - 使用 .NET WebAPI 最佳实践进行进程间通信
- javascript - 如何在javascript中修复每日更新程序
- java - JTable 记录不显示
- google-apps-script - Google 应用程序独立脚本 - 文件选择器身份验证失败