Reputation: 300
I am trying to apply TDD for a small change request in my code. Since it is an existing code with absolutely no Unit Test cases around it. I need help with the below scenario.
Consider the example ( C# code sample ):
private void main()
{
//some existing code logic
existinglogicA();
existinglogicB<some_inlinecode>;
existinglogicC<some_inlinecode>;
//Say, I am going to add new code logic here to follow the upward code workflow
newlogicX();
existinglogicD<some_inlinecode>;
existinglogicE();
}
Questions: 1. Should I expose "newlogicX()" as public method to Unit Test It? 2. Should I take the trouble to add Unit Test for the whole routine "main()"?
Upvotes: 1
Views: 66
Reputation: 6392
There are a couple of possible approaches here. For a broader discussion you should look into Michael Feather's book Working Effectively With Legacy Code.
You could easily make the method public, yes. The downside there is that the public interface to your class grows and you may not want to expose this particular method on its interface. The deciding factor is generally whether the method makes sense as a responsibility of the class, even if its only use in production is within the class. If it does then you lose nothing by making it public and you gain in terms of testability.
If not, then your best bet is to extract the method to a new class, one where the method does make sense as an API member. Then you can test the functionality of the new class in isolation of the class where its used. The benefit here is that the logic in the new class can more easily be tested and the old class can have some kind of mock or fake injected, giving you a potentially useful test seam for controlling behaviour in tests of the old class.
The drawback of extracting to a new class is that, as you suggest, you'll find the new class has some kind of temporal dependency on how things happen in the old class - i.e. you end up with tight coupling between method calls on the old class and methods on the new class. Realistically, however, that design flaw exists and the new class structure is merely highlighting the flaw. What you've gained, however, is that the new class structure is more testable and, as a result, slightly easier to refactor towards a better design which doesn't exhibit this kind of problem.
tl;dr - one way or another you should make the method public, either on this class or on another one.
Upvotes: 1
Reputation: 6998
If that's your structure then make it public. What difference does it matter if it's public or private given the structure of that code?
Upvotes: 0
Reputation: 8861
If you can - better write test for just newlogicX
method. In that case, if you miss something in test - it would be easier to deal with it later.
Upvotes: 0