On Programming and Testability

Posted on September 21, 2016 by Richard Goulter

I’ve been reading some interesting blogposts recently:

My fresh, recent understanding of this last point is that in order to be able to inject things, constructing/initialising objects (using “new”) within methods is bad.

class SomeInterestingClass {
  // ...
  public function computeSomething($x) {
    $service = new ServiceFromOtherModule(); // Can't be changed in here
    return $service->compute($this->val, $x);

The way to replace this, then, would be to store $service as a property, initialised in constructor instead of “where it’s used”, which can be set. And maybe some more complicated variation for if this class we depend on needs to be initialised with variables the constructor.
– The same more/less applies if the ‘dependency’ is a function call, etc.

My understanding is, then, that for non-trivial computations, “testing behaviour” comes down to assertions on how mocked-up classes/functions are used. Some white-box understanding of how behaviour is implemented is needed to know what can be stubbed. – This somewhat makes unit tests a ‘declarative’ companion to the code: “In this circumstance, this should happen”.

Rephrasing the above in roughly terms of ‘information-flow’: I’m guessing that at least some white-box knowledge of what kinds of messages are received (from what kind of sender), what kinds of messages are sent (to what kind of recipient) is an inevitability; perhaps it’s that it becomes a tautology when the mocking explicitly (albeit limitedly) declares the same messages/relations which the SUT code does.

– But I don’t know. It’s something I’d like to think about some more.

Newer post Older post