tylerssn
6 months ago

How to Mock hasMany() resonse

Posted 6 months ago by tylerssn

I have test that attempts to mock a call to a hasMany() relationship (versions() below). The problem is that first() on the relationship always returns null.

    public function testGetDefaultVersion()
    {
        /**
         * Mock Config::get('docs') and assert that it will be called in this test at some point
         */
        $repoId = 'main';
        /**
         * @var Documentation $documentationMock
         */
        $documentationMock = factory('App\Documentation')->make(['id'=>0,'label'=>$repoId]);

        $documentationVersions = new Collection([
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'development']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'main']),
            factory('App\DocumentationVersion')->make(['documentation_id'=>0, 'version' => 'yas yas yas']),
        ]);

        DocumentationFacade::shouldReceive('where')->with('label', $repoId)->once()
            ->andReturn(new Collection([$documentationMock]));
        DocumentationFacade::shouldReceive('versions')->once()
            ->andReturn($documentationVersions);

        $actualDefaultVersion = $documentationMock::getDefaultVersion('main');
        $this->assertIsString($actualDefaultVersion);
    }

The static getDefaultVersion() method looks like this:

public static function getDefaultVersion(string $repo): string
    {
        return (string) Facades\Documentation::where('label', $repo)
            ->first()
            ->versions()
            ->first()
            ->version;
    }

Please sign in or create an account to participate in this conversation.