Unit testing and additional code change

Hi,

how do you guys handle the following scenario?

You have a class you’re testing:


class Foo {
  public function add() {
    $a = 1;
    $b = 2;

    return $a + $b;
  }
}

class FooTest extends PHPUnit_Framework_TestCase {
  public function testAdd() {
    $o = new Foo();

    $this->assertEquals($o->add(), 3);
  }
}


At the time written, there was no additional object being used except for whatever was already provided at the constructor level (if any).

At a later time the method needs to do a little more:


class Test {
  public function add() {
    $a = 1;
    $b = 2;
     
     $o = new Bar();
     $o->($a, $b); // maybe passed by reference?

     return $a + $b;
  }
}

How would you handle the dependency? Leave it as is? I wouldn’t be able to mock it. Pass it as a parameter of that method? What is the best way of keeping maintenance easy on all developers who deal with this code?

For me, the obvious choice would be to pass it as a parameter of that method.

I’m interested in hearing everyone’s opinion as I run into this situation ~25% of the time.

Thanks!

Hi…

You want the minimum of scope wherever possible. Your instincts are correct, pass it in the method if possible.

If you then find you are constantly passing the object in, so much that the caller has a management burden from it, then you have to go to the next scoping level. That is, to pass it in the constructor.

The next scoping level is global. Obviously you don’t want to go there :(.

yours, Marcus