I’m trying to write a unit test for a PHP script that does not contain any functions or classes.
It is just a plain PHP script that returns header('Location: ${url}')
when a specific condition is met.
<?php
error_reporting(0);
include XOOPS_ROOT_PATH . "/include/curl/functions.php";
include "ADBConnection.php";
include "MDBConnection.php";
global $user;
if (!empty($user) && is_object($user)) {
$a_connection = new ADBConnection();
$m_conn = new MDBConnection();
$conn = $a_connection->getConnection();
$a_connection->setSqlQuery($some_sql);
$prepare = $conn->prepare($db_connection->getSqlQuery());
$prepare->execute([
"user_id" => $user->customer_id(),
]);
$result = $prepare->fetchAll();
$is_allow = false;
if (!empty($result)) {
foreach ($result as $item) {
if ($item['is_allow'] > 0) {
$is_allow = true;
break;
}
}
}
$user_admin = $m_conn->getUserAdmin($user->uid());
if ($is_allow || $user_admin === true) {
header("Location: ${some_url}");
} else {
header("Location: ${another_some_url}");
}
} else {
header("Location: /");
}
Below is what I’ve tried to write a test case for that script file.
protected function setUp()
{
parent::setUp();
$this->userMock = $this->getMockBuilder(User::class)
->setMethods(['customer_id', 'uid'])
->getMock();
$this->axDatabaseMock = $this->getMockBuilder(ADBConnection::class)
->setMethods()
->getMock();
$this->marcDatabaseMock = $this->getMockBuilder(MDBConnection::class)
->setMethods(['getUserAdmin'])
->getMock();
}
public function test_redirect_user_to_some_url_page()
{
$this->userMock->method('customer_id')
->willReturn(1);
$this->userMock->method('uid')
->willReturn(1);
$this->marcDatabaseMock->method('getUserAdmin')
->willReturn(true);
ob_start();
require('path_to_script');
$headers = xdebug_get_headers();
$this->assertContains('Location: ${some_url}', $headers);
}
When I tried to debug the returned value of $headers it gave me this:
array(1) {
[0] =>
string(38) "Content-type: text/html; charset=UTF-8"
}
It seems like it does not return an expected result.
So how can we write unit test for a PHP file script?
I also checked with other answers but didn’t figure it out.