We are encouraging to write tests. To cover your code. To decrease uncertainty.
Yet, I’m still seeing a lot of articles where someone shares his knowledge about particular features and… he shows how the code works using main() method:
public class WhateverApp { public static void main(String[] args) { DescribedFunctionalityProvider provider = new DescribedFunctionalityProvider(); Result result = provider.showHowYouDoingThings(); System.out.println(result.showThatReallyWorks()); } }
I’ve got one simple question – why?
We are encouraging new developers who just joined our projects, who just started to code to write tests and when they’re looking for knowledge, when they’re reading articles they see… no tests at all (except the articles on how write a test).
Why are we telling one and showing different approach?
Why not just write:
public class DescribedFunctionalityProviderTest { @Test public void shouldShowThatDescribedFunctionalityReallyWorks { Result expectedResult = //code that builds expected result DescribedFunctionalityProvider provider = new DescribedFunctionalityProvider(); Result result = provider.showHowYouDoingThings(); assertThat(result.showThatReallyWorks()).isEqualTo(expectedResult); } }
There’s no more code. It’s not harder. It’s not more complicated.
In my opinion the only difference is that doing it this way is learning it in the right way.
When new developers see the approach with main() method, they’re starting to believe that it’s the right approach.
“If everyone is doing it, why the heck those few devs in this project are so test- oriented? If there were any value in it, everyone would follow these practices.”
When you are proving the piece of code works via main() method, you are teaching all those who are reading your posts this “testing strategy”. After a few articles it will become a habit. A wrong habit. And probably you know as well as I do that eradicating a bad habit is extremely hard.
Another problem is that they are learning to display all results. Not verifying the result, not comparing it with expectation. No, they will print it out.
I believe that teaching the “main method testing strategy” is not your goal when you’re writing articles or when you are otherwise sharing your knowledge.
I believe that you not only want to learn how to write code, but also how to do it well.
So even harder than I encourage everyone to write tests, I encourage those who are writing blogs, who are learning, who are sharing the knowledge – test your code, not put it into main()!
No comments:
Post a Comment