Я пишу тесты для своего PHP-приложения, но у меня возникли проблемы с передачей данных на мой контроллер с помощью file_put_contents("php://input", ...). Функция должна прочитать входные данные (php://input) и найти пользователя по предоставленному идентификатору, но она всегда возвращает ошибку о том, что входные данные неполны.
Тестовый класс: Вот мой тестовый код с использованием PHPUnit:
class UsuarioControllerTest extends TestCase
{
protected function setUp(): void
{
$this->usuarioMock = $this->createMock(Usuario::class);
$this->usuarioController = new UsuarioController($this->usuarioMock);
}
public function testFindByIdReturnsUserWhenUserExists()
{
$userId = 2;
$userData = ["id" => $userId, "nome" => "Jon Doe"];
// Mock the method that retrieves user by ID
$this->usuarioMock->method('findById')->with($userId)->willReturn($userData);
// Simulate setting input as JSON
$_SERVER["CONTENT_TYPE"] = "application/json";
file_put_contents("php://input", json_encode(["id" => $userId]));
// Capture the output
ob_start();
$this->usuarioController->findById();
$output = ob_get_clean();
// Assert the response matches the expected JSON
$this->assertJsonStringEqualsJsonString(json_encode($userData), $output);
}
}
Метод контроллера: вот метод findById в моем контроллере:
public function findById()
{
$data = json_decode(file_get_contents("php://input"));
if (isset($data->id)) {
try {
$user = $this->usuario->findById($data->id);
if ($user) {
http_response_code(200);
echo json_encode($user);
} else {
http_response_code(404);
}
} catch (\Throwable $th) {
http_response_code(500);
}
} else {
http_response_code(400);
}
}
Подробнее здесь: https://stackoverflow.com/questions/791 ... s-in-phpun