Farid Movsumov
Farid Movsumov

Reputation: 12725

Testing constructor

My constructor sets property with data which loaded from database. How can I test if it really load data from db? I want %100 test coverage rate so I need test every piece of my code.

<?php
class PreferencesAdapter {

    private $_preferences = NULL;

    public function __construct() {         
                ...
        $this->load();
                ...
    }

    public function load() {
        ...
        $this->_preferences= DataFromDb();
    }
}
?>

Upvotes: 0

Views: 320

Answers (2)

olleolleolle
olleolleolle

Reputation: 1946

(In the interest of fast tests, here is a wordy approach you could do.)

Or, put your relevant queries as public methods in a class PreferencesAdapterQueryCollection, and inject it as an optional constructor parameter to PreferencesAdapter. (If the parameter was not sent in, just instantiate the PreferencesAdapterQueryCollection right there.)

In PreferencesAdapterTest, send in a mocked PreferencesAdapterQueryCollection, with expectations and return values on its public, simple query methods.

I like Mockery for this. See the question Mockery - call_user_func_array() expects parameter 1 to be a valid callback for example invocation.

Upvotes: 0

cweiske
cweiske

Reputation: 31078

I'd mock load() in a test method and verify that it gets called once when creating the object.

Upvotes: 1

Related Questions