Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing concrete classes

I have inherited a project that has no interfaces or abstract classes i.e. concrete classes only and I want to introduce unit testing. The classes contain lots of functions, which contain business logic and data logic; breaking every rule of SOLID (http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29).

I had a thought. I was thinking about creating interfaces for each of the poorly designed classes, exposing all functions. Then at least I can Mock the classes.

I am relatively new to Unit Testing (I have experience with a project, which was very well developed using interfaces in the right places). Is it a good idea to do this i.e. create interfaces for all the concrete classes (exposing all the functions and sub routines), just for unit testing?

I have spent some time researching this but I have not found an answer.

like image 688
w0051977 Avatar asked Aug 26 '13 18:08

w0051977


2 Answers

If your project has no tests at all, before adding any unit tests I'd much rather create higher level tests (i.e acceptance, functional and/or integration tests).

When you have those tests in place you know that the system is behaving as it should and also that it has certain level of 'external' quality (meaning by this that the inputs and outputs of your program are the expected ones).

Once your high level tests are working, you could try to add unit tests to the classes that already exist.

I bet that you will find yourself in the need to refactor some of the existing classes if you want to be able to unit test them so you can use your high level tests as a safety net that will tell you if you've broken anything.

like image 95
jsanchez Avatar answered Sep 19 '22 22:09

jsanchez


This is a tough thing to tackle. I think you are on the right track. You'll end up with some ugly code (such as creating header interfaces for each monolithic class), but that should just be an intermediate step.

I'd suggest investing in a copy of Working Effectively with Legacy Code. First you could start by reading this distillation.

In addition to Karl's options (which let you mock via interception), you could also use Microsoft Fakes & Stubs. But these tools will not encourage you to refactor the code to adhere to SOLID principles.

like image 38
Matt Avatar answered Sep 18 '22 22:09

Matt