What is CodeIgniter 4 testing mock services?
Answer
CI4's testing infrastructure allows mocking services to isolate units under test. The key method is Services::injectMock("email", $mockEmail) — after this call, any code that calls service("email") gets the mock instead. Use PHPUnit mocks: $mockEmail = $this->createMock(\CodeIgniter\Email\Email::class); $mockEmail->method("send")->willReturn(true); Services::injectMock("email", $mockEmail). Reset mocks after test: Services::reset(). For models: Factories::injectMock("models", "UserModel", $mockModel). For the database: use an in-memory SQLite database configured in app/Config/Database.php under the tests group. CI4's DatabaseTestTrait wraps each test in a transaction and rolls it back — faster than recreating the schema. Mock the Request with custom data: $this->request->setGlobal("post", ["name" => "Alice"]).
Previous
What is CodeIgniter 4 API rate limiting?
Next
What is the Benchmark class in CodeIgniter 4?