模拟对同一 class 中另一个函数的函数调用

Mock out function call to another function in same class

我有一个函数可以调用同一个 class 中的另一个函数。我正在尝试测试是否在我的单元测试中调用了该方法,但是找不到模拟它的方法。

这里是方法调用的例子

public function follow($user_id, $followsfeed, $target_user_id)
    {
        $news_feeds = $this->getNewsFeeds($user_id);

    }

我想模拟 getNewsFeed 方法并断言它在我执行 follow 时被调用。

实现此目标的最佳方法是什么。因为我无法锻炼如何创建内部模拟对象。

您可以使用 partial mocks 作为测试的示例 class,您可以这样做:

public function test_follow()
{
    $mock = Mockery::mock('App\Services\SomeService')->makePartial();
    $mock->shouldReceive('getNewsFeeds')
      ->once()
      ->with("id1","id2")
      ->andReturn($someNews);
    $mock-> follow("id1","id2"); 
}

您也可以使用 PHPUnit test-doubles

希望对您有所帮助