Search code examples
phpunit-testingkohanaphpunitvisibility

How to test constructor that sets protected properties?


Well, I'm new to unit-testing (with phpUnit) and just started to test one class of mine.

Actual constructor looks like this:

/**
 * Loads configuration.
 */
function __construct() {

    $config =
        Kohana::$config->load('koffee');

    $this->_table_name = $config->table_name;
    $this->_table_columns = $config->table_columns;

}

It basically gets configuration from another file and sets it as protected properties to that object.

Here is how unit-test looks (it's not finished and that's where I need help):

/**
 * Tests that config is loaded and correct.
 */
function testConfigIsLoadedAndCorrect() {

    $object = new Model_Article();

    $config = Kohana::$config->load('koffee');

    // Compare object's **protected** properties to local `$config`. How?!

}

The problem is that properties are protected and I cannot access them so easy...

Possible solutions I see at the moment:

  1. Change visibility of properties (I don't like this),
  2. Add, so called, "getters" to class I test - not unit-test (I don't like this neither);

Probably this is funny to you, but, as I said, I'm new to unit-tests. Any help much appreciated.


Solution

  • Unit-testing is about unit testing. Protected members are not part of the public interface of a unit, which is all you should need to care about when writing unit tests.

    You don't test the inner guts of a unit, but that it works as expected.

    If you regardless of that want to do such stuff, you can use Serialization­Docs, casting to array and Reflection­Docs to inspect protected/private properties of an object or to execute protected/private methods of an object.


    See as well: PhpUnit private method testingSO Q&A