James's avatar

How to test this method

I have a repository class which has the eloquent model injected into its constructor. In my getById() method, I use a protected mapEntity() method which maps the returned eloquent model to my post entity.

The method looks like:

    public function getById($postId)
    {
        $eloquentPost = $this->posts->where('id', $postId)
                            ->with(['tags'])
                            ->first();

        return $this->mapEntity($eloquentPost);
    }

In my test class, I mock the eloquent post model and then check what methods are called on it:

    public function testGetById()
    {
        $this->posts->shouldReceive('where->with->first');
        $this->postRepository->getById(99);
    }

This is fine, until the mapEntity() method is called and then it obviously can't map the eloquent object as it isn't returned. I don't want to test the mapEntity() method here so I don't want to force the mock to return something.

I did think about making the mapEntity() method a separate factory class but decided since it was quite simple, I'd do it in this class, it is protected because I don't want to be able to call eloquentPostRepository->mapEntity() from outside the class.

Is moving it out into the separate factory the best method or is there another way?

0 likes
1 reply

Please or to participate in this conversation.