shine
shine

Reputation: 35

How to test this function?

public static function flush_cache()
{
    static::$_cached_objects[get_class()] = array();
}

I don't know how to test this with phpunit? The project is a Fuelphp Framework . can you give some advice instead of trampling on my question? thanks a lot

Upvotes: 0

Views: 51

Answers (1)

exhuma
exhuma

Reputation: 21747

There is no "correct" way to test this. The reason for that is: you have global state!

Testing static values is fairly difficult because they share state between unit-tests (during one test-run). So one unit-test can interfere with another and execution-order of unit tests becomes important.

Instead of using a static value (which is nothing else than global state), you should pass the cache into the function (like dependency injection). I that case, you would have something like this:

public static function flush_cache($cache) {
    $cache = array();
}

// the test function
public function testFlushCache() {
    $myCache = $array();
    // do something which uses the cache, filling up some values.
    flush_cache($myCache);
    $this->assertEquals(count($myCache), 0);
}

Of course, you then have to still take care about instantiating your cache in your application.

But I strongly suggest to avoid global state, like the static cache (having the static function is okay though). Having global state makes testing a PITA, and can also be a source of weird bugs because each function tapping into the global variable becomes non-deterministic.

Upvotes: 2

Related Questions