ealeon
ealeon

Reputation: 12452

Is it best practice to modify the production code to be testable / solely for testing purposes?

currently in production code, I have a function as such

public void doWork() {
    ... call functionA
    ... call functionB
    ... do other work
}

I have to test a case where I need to pause after functionA is called in doWork(). And there is no way for me to pause through testing framework

so I've changed the production to be

public void doWork() {
    doWork(new CountdownLatch(0))
}
public void doWork(CountdownLatch latch) {
    ... call functionA with a latch and functionA calls latch.await()
    ... call functionB
    ... do other work
}

Now, i can create a test case and test with doWork(new CountdownLatch(1))

But in production it will always be calling doWork() which in turn calls doWork(new CountdownLatch(0))

Is this unnecessary overhead just to be able to make the code test-able? or is this acceptable?

Upvotes: 1

Views: 393

Answers (1)

Januson
Januson

Reputation: 4841

Modification of your code in order to make it testable is completely valid. Test is just another client of your code and as such provides feedback on the usability of the code.

On the other hand for the feedback to be constructive, test has to abide to some rules. Such as it should test behavior of the code and not its internals.

Now, for the actual testing you have more options.

  • Most strait-forward would be to use a test double for its dependencies. You mentioned that the functionA is final and so it cannot be mocked. It can. While not ideal solution both Mockito 2.+ and PowerMock support mocking of final classes.
  • Cleaner way would be to listen to your tests. Your tests are telling you that your code has design problems. Maybe you could fix those. You could for example try to separate threading and execution logic so that it can be tested. Or you could introduce an interface to make dependencies mockable.

Upvotes: 2

Related Questions