Question

I have a simple method inside of a class that does the following

 class ToBeTested
 {
      public function getLocalSettings()
      {
          require_once 'local.php';

           return (isset($configSetting['foo'])) ? true : false;
      }
 }

in local.php

 <?
      $configSetting = array(
           'foo' => '1',
           'bar' => 'false',
      );

I'm looking to create the unit test for getLocalSettings. I realize this is sortof like dependency injection, but I can't quite wrap my head around how I should write the test. It seems like a pretty trivial block of code to get overly complicated with the tests but I have the freedom to refactor however here, and I want to replace 'local.php' with my own values/data provider for testing purposes

EDIT FOR CLARITY/COMMENTS

I used a config as a sample here, but what we're actually using is a huge file that's being output from a database and being included as a datasource, and parsed in this function. I wrote a simplified version of it to avoid overcomplicating the question, but the included array is several megs and not actually 'just a config file'. Solutions that give different approaches at handling file configs aren't helpful unfortunately, but a way to inject this array will work just fine (but at some point I'll need to run that 'require'.

Thanks

Was it helpful?

Solution

You should inject your configuration array into the ToBeTested class either via the constructor or a setter. This will eliminate the side effect caused by getLocalSettings (the inclusion of another file) and will allow you to mock the settings whilst testing. Your class definition might look like this:

class ToBeTested
{
    private $localSettings;

    public function __construct($localSettings)
    { 
        $this->localSettings = $localSettings;
    }
}

Then, when instantiating this class via normal use, you simply provide the configuration array to the constructor (the inclusion of local.php should be done in bootstrap code). When you want to unit test the class, you can inject any set of settings you need to when instantiating it, and you'll have no hard dependency on the filesystem. You might choose to use the data provider functionality in PHPUnit (documentation) for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top