views:

138

answers:

3

Hi! So which is better. Do we start letting Tests design our code. Do we start introducing constructor injection for dependencies just to make code testable? or do we use the "override" protected method & sub class the class under test.

+3  A: 

I generally think that testable code is good code. For code to be testable, you need better decoupling so each component can be tested in isolation with a test harness. However, there shouldn't be code in the implementation that is just used by the unit tests.

Also, keep in mind that what you need to test is the public API of an object, not it's protected/private methods. Finding bugs in private/protected method should be what logging/debuggers are for. After all, a bug in those will also propagate up to the public methods. So as long as the public methods fulfill tests, the protected methods will be covered too.

If you are using java, and have package scoped classes that implement public interfaces in the same package, I would put the unit tests in the same package in a separate folder to test those classes. You can also put unit tests in the same package as the tested class to test protected methods.

Staale
A: 

I mostly agree with Staale, well-designed code should be testable.
I don't use constructor injection or derive classes for testing. I believe using 'service locators' is the right way to do dependency injection.

Sergey Volegov
A: 

If your tests are well designed, they will emulate real-world usage. Therefore a really good suite of unit tests that will cover every conceivable way an app could leverage your code will should result in a robust implementation. If your tests are flawed, then you are not gaining much.

ZombieSheep