In my handlers I return JsonResponse
For example:
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$data = [
// ...
];
return new JsonResponse($data);
}
Then I have a ResponseFormatterMiddleware, which slightly changes response format:
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);
if ($array = $this->getArray($response)) {
$formatType = $request->getQueryParams()['format'] ?? null;
$formatType = $formatType ? mb_strtolower($formatType) : null;
if ($formatType === 'xml') {
return new XmlResponse($this->toXml($array));
}
if ($formatType === 'txt') {
return new TextResponse($this->toTxt($array));
}
return new JsonResponse([$this->rootElement => $array]);
}
return $response;
}
Now I can’t test it. Ok, I spied how others are testing middlewares:
public function test()
{
$request = $this->prophesize(ServerRequestInterface::class);
$handler = $this->prophesize(RequestHandlerInterface::class);
$handler->handle($request->reveal())->will([$this->response, 'reveal']);
$result = $this->middleware->process($request->reveal(), $handler->reveal());
$this->assertSame($this->response->reveal(), $result);
}
Well, the test passes, but it does not test anything.
I want to mock the request and compare it with the answer.
public function test()
{
$request = $this->prophesize(ServerRequestInterface::class);
$this->stream->getContents()->willReturn('{}');
$request->getBody()->willReturn($this->stream);
// $request->reveal()->getBody()->getContents() - {}, ok
$handler = $this->prophesize(RequestHandlerInterface::class);
$handler->handle($request->reveal())->will([$this->response, 'reveal']);
$result = $this->middleware->process($request->reveal(), $handler->reveal());
// $result->getBody() - null, not ok
$this->assertEquals('{"main": "null"}', $request->getBody()->getContents());
}
Why can’t I get a response from my Middleware?