内部采用静态法的phpunit试验方法

内部采用静态法的phpunit试验方法,php,unit-testing,phpunit,Php,Unit Testing,Phpunit,我想模仿Carbon::now()和Transaction::where…(laravel中的雄辩模型)。可能吗?我不知道在没有依赖注入的情况下如何编写代码 class SomeClass { public function getLatest() { $cacheTime = Carbon::now(); if ($cacheTime > 'xxxx') { return 'abcdefgh'; }

我想模仿
Carbon::now()
Transaction::where…
(laravel中的雄辩模型)。可能吗?我不知道在没有依赖注入的情况下如何编写代码

class SomeClass
{
   public function getLatest()
   {
        $cacheTime = Carbon::now();

        if ($cacheTime > 'xxxx') {
            return 'abcdefgh';
        }

        return Transaction::where('base', '=', 'asas')
            ->where('target', '=', 'bbbb')
            ->orderByDesc('created_at')
            ->first();
   }
}

您可以轻松地模拟碳:

因此,在单元测试中,只需调用
Carbon::setTestNow($knownDate)在函数调用之前。
诸如此类:

public function testGetLatest()
{
    $knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
    Carbon::setTestNow($knownDate);  
    $someClass = new SomeClass;

    $result = $someClass->getLatest();

    ...
}
我认为您不能在代码中模拟
事务::where
,这样做没有任何目的。
where
orderByDesc
只用于设置查询。
first
函数将实际返回
事务
对象。即使您可以先模拟或存根
函数
,那么您的测试也毫无用处,因为您正在测试
getLatest
函数是否返回由您创建的某种模拟对象

这实际上是集成测试的一个很好的例子,Laravel提供了各种有用的工具,使集成测试变得更容易。查看此链接:


什么样的库是
事务
?请提供链接或完整名称空间.App\Transaction(Larave模型)。SomeClass是service App\Services\SomeClass也许你有一些想法可以在雄辩的模型上创建mock?我正在努力。。。而且没有效果
public function testGetLatest()
{
    $knownDate = Carbon::create(2001, 5, 21, 12);          // create testing date
    Carbon::setTestNow($knownDate);  
    $someClass = new SomeClass;

    $result = $someClass->getLatest();

    ...
}