Files
alrahma_sunday_school/tests/app/Controllers/Api/EmergencyContactControllerTest.php
2026-02-10 22:11:06 -05:00

105 lines
3.3 KiB
PHP

<?php
namespace Tests\App\Controllers\Api;
use App\Controllers\Api\EmergencyContactController;
use App\Models\ConfigurationModel;
use App\Models\EmergencyContactModel;
use CodeIgniter\Test\CIUnitTestCase;
class TestableEmergencyContactController extends EmergencyContactController
{
public function setModels(EmergencyContactModel $model, ConfigurationModel $config): void
{
$this->emergencyContactModel = $model;
$this->configModel = $config;
}
}
class EmergencyContactControllerTest extends CIUnitTestCase
{
private $controller;
private $contactModel;
private $configModel;
protected function setUp(): void
{
parent::setUp();
$this->contactModel = $this->createMock(EmergencyContactModel::class);
$this->configModel = $this->createMock(ConfigurationModel::class);
$this->controller = new TestableEmergencyContactController();
$this->controller->setModels($this->contactModel, $this->configModel);
}
public function testIndexFiltersByParent()
{
$query = $this->makeRequest('GET', '/api/v1/emergency-contacts', ['parent_id' => 9]);
$this->controller->setRequest($query);
$this->configModel->method('getConfig')->willReturnMap([
['school_year', '2024-2025'],
['semester', 'Fall'],
]);
$this->contactModel->method('where')->willReturnSelf();
$this->contactModel->method('findAll')->willReturn([
['id' => 1, 'parent_id' => 9, 'cellphone' => '5551234'],
]);
$response = $this->controller->index();
$this->assertTrue($response['status']);
$this->assertCount(1, $response['data']);
}
public function testShowReturnsNotFound()
{
$this->contactModel->method('find')->with(5)->willReturn(null);
$response = $this->controller->show(5);
$this->assertFalse($response['status']);
$this->assertEquals(404, $response['code']);
}
public function testCreateValidContact()
{
$payload = [
'parent_id' => 5,
'emergency_contact_name' => 'Hakim',
'cellphone' => '555-1234',
'relation' => 'Uncle',
'school_year' => '2024-2025',
'semester' => 'Fall',
];
$req = $this->makeRequest('POST', '/api/v1/emergency-contacts', $payload);
$this->controller->setRequest($req);
$this->configModel->method('getConfig')->willReturnMap([
['school_year', '2024-2025'],
['semester', 'Fall'],
]);
$this->contactModel->method('insert')->willReturn(99);
$this->contactModel->method('find')->with(99)->willReturn([
'id' => 99,
'emergency_contact_name' => 'Hakim',
]);
$response = $this->controller->create();
$this->assertTrue($response['status']);
$this->assertEquals('Emergency contact created successfully', $response['message']);
$this->assertEquals(99, $response['data']['id']);
}
public function testCreateInvalidPayload()
{
$req = $this->makeRequest('POST', '/api/v1/emergency-contacts', []);
$this->controller->setRequest($req);
$response = $this->controller->create();
$this->assertFalse($response['status']);
$this->assertEquals(422, $response['code']);
}
}