Skip to content

Provide a mock message factory #20

Closed
@soullivaneuh

Description

@soullivaneuh
Q A
Bug? no
New Feature? yes
Version v1.0.1

Some times we don't care of the content of any response given by the mock client during the test, but the default null body does not feed the needs.

Currently, if the response we want to change is after 42 calls, we have to set 42 fake response to return the good one. But we don't care about the 41 firsts.

Having a MockMessageFactory with a default response would be a good solution. Here is a quick one:

use Http\Discovery\MessageFactoryDiscovery;
use Http\Message\MessageFactory;
use Psr\Http\Message\ResponseInterface;

final class MockMessageFactory implements MessageFactory
{
    /**
     * @var MessageFactory
     */
    private $responseFactory;

    /**
     * @var ResponseInterface|null
     */
    private $defaultResponse;

    public function __construct()
    {
        $this->responseFactory = MessageFactoryDiscovery::find();
    }

    /**
     * @param ResponseInterface|null $defaultResponse
     */
    public function setDefaultResponse(?ResponseInterface $defaultResponse)
    {
        $this->defaultResponse = $defaultResponse;
    }

    /**
     * {@inheritdoc}
     */
    public function createRequest(
        $method,
        $uri,
        array $headers = [],
        $body = null,
        $protocolVersion = '1.1'
    )
    {
        return $this->responseFactory->createRequest($method, $uri, $headers, $body, $protocolVersion);
    }

    /**
     * {@inheritdoc}
     */
    public function createResponse(
        $statusCode = 200,
        $reasonPhrase = null,
        array $headers = [],
        $body = null,
        $protocolVersion = '1.1'
    )
    {
        if ($this->defaultResponse) {
            return $this->defaultResponse;
        }

        return $this->responseFactory->createResponse($statusCode, $reasonPhrase, $headers, $body, $protocolVersion);
    }
}

And the implement on a Symfony kernel test case:

$this->getContainer()->get(MockMessageFactory::class)->setDefaultResponse(new JsonResponse([]));

In this case, the JsonResponse would be always returned.

It can be the default response factory has this one will fallback to a real one if no default response is provided.

WDYT? I may propose a PR for that.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions