Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting class when TDD'ing. How to test the new extracted class?

So I had a couple of methods in my main class that used a matrix to set pixels on or off. I got all my current tests running and so, and I've decided it's already time to pull out some of that logic related to the matrix and such and create a Matrix class.

My question is, besides the tests I currently have for my SUT class (I'm just in the beginning, so I currently only have one class, the SUT's main one), should I create Unit-Tests for it? If so, how do you do it? I mean, do I let all my code as it is right now, create make unit tests one by one doing test first approach until I see I have all the functionally I want in it and only there I refactor my code? I just straight create the Matrix class and just make sure the old tests are still passing and that everything's ok?

Thanks

like image 346
devoured elysium Avatar asked Dec 02 '22 04:12

devoured elysium


2 Answers

Basically the latter. There is no need to test a class just because it is defined as a distinct class. If you are refactoring without adding any functionality or otherwise changing behavior, the only reason to add tests is if you lack confidence in a certain part of the code. Otherwise, the code is already under test, and the fact that it is tested via another class should not matter.

That being said, there are times where the structure of the code has changed so much that for organizational purposes you want to move the test, so you can tell where this piece of code is actually being tested from. But that is a different question from saying that "this is an independent unit, so it must have independent tests."

like image 196
Yishai Avatar answered Dec 06 '22 09:12

Yishai


One relatively common hint that it's time to sprout a class is that you've got private methods you want to test. In that situation, let the tests really drive the refactoring. Write the test for the (currently private) method in the (as yet unwritten) class; give an instance of the new class to the existing class and move the private method into the new class, making it public as you go.

like image 44
Carl Manaster Avatar answered Dec 06 '22 09:12

Carl Manaster