views:

150

answers:

1

hi

i have old code which didnt use TDD now i want to write a test for a function which looks like this

function somefunction($someargs){
    // do a few checks on $someargs
    $database = new DB_PG();
    $result = $database->select($query);
    // do some changes on result
    return $result;
}

since im not much expirienced with phpunit and testing in general my question is: how can i mock DB_PG? i tried getMock() in my test, but since the function uses "new" to get an instance my mock object is ignored, which makes sense

so i see only 2 options

  1. some features of phpunit i dont know - which is the reason i ask here ^^
  2. i have to modify the old code - which i know would be better

so, anyone knows an answer for option 1?

thx all

A: 

OPTION 1

Can you change the function to work as follows:

function someFunc($existingArgs, $db = null)
{
    $db = (is_null($db)) = new DB_PG();
    $result = $db->select($query)

    $return $result;
}

This way you can pass in a db instance, this lets you at least test this function, in the future you can refactor things such that someFunc's work is on models, and the db load stuff happens via a dao/repository/factory.

OPTION 2

If DB_PG isn't already pulled in via a require/include in the file where this function lives, you can define a dummy class inside your test class

class DB_PG
{
    public function select($query)
    {
        //use phpunit's libs to output a mock object, you'll need to use the PHPUnit_Framework_Mock::generate() static method, I think that's the name.
        return $mockResult;
    }
}

That way you can control what happens with the result.

Saem