php - Is it possible to mock "require" or "require_once" statement with Kahlan?


I have very old legacy code. Before starting refactoring I want to make some unit tests for the code. But the bad thing is that files relies on each other with "require_once" statements (hovewer, functions I want to test is isolated).

So I can't write normal tests if I will not be able to mock "require_once" statement.

I'm using Kahlan framework for testing. So is it possible to mock such statements? If yes, than how?




It was not possible.

However, I have made a plugin to Kahlan that allows to "extract" functions from any file and skip all other code. It will not allow to exactly "mock" statements, but it will allow to test isolated functions. I made pull-request and if it will not be accepted, I will make a separate packagist composer packet and update this answer.

Changes can be found here:

Example of usage:


require_once 'something';  // This string will be "skipped" on test

do_something();  // This string too

function test()
    return 42;

Test for this file with plugin:


use Kahlan\Plugin\Isolator;


describe('test()', function() {
    it('returns 42', function() {

People are also looking for solutions to the problem: php - In Laravel how can I validate the count of multiple file upload


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.