user3886650
user3886650

Reputation: 159

PHPunit test a config file reader

I have a class which reads a config file (array).

Here's a basic example:

class ConfigReader 
{
    function __construct($configFileName)
    {
         $this->config = $this->load($configFileName);
    }

    private function load()
    {
         //load config file
    } 

    public function hasValue($value)
    {
         //parse config for value return true
    }

    public function getValue($key)
    {
         //etc....
    }
}

How should I should I unit test this? Should I mock the config file? I assume not because if I change something in the real config file the test would not pick it up...If I should mock it how should I test the config file?

Upvotes: 0

Views: 844

Answers (1)

Schleis
Schleis

Reputation: 43750

Dealing with the filesystem is tricky. There are a couple of ways to test this.

One have a test config file that you would use in your test that contains example values. I am not sure what exactly you are going to do with the values. That may require mocking other system values. The down side to this is that you are maintaining a file for testing and have to make sure that paths/permissions of the file are such that the test can run. You can end up with the test failing because the file wasn't readable rather than an actual problem.

The preferred way would be to mock the filesystem. PHPUnit's documentation recommends using vfsStream. This would allow you to create a config file in your test on the fly and try to load it. The advantage this has is that you don't have to maintain the separate file system/paths for loading the file.

I am not able to provide more detail without having a better idea of what your class methods are trying to accomplish. But this should get you on the right start.

Upvotes: 2

Related Questions