Is there a way to strip the JUnit @Test code from my Java class. At the moment I embedded the test code in the same file as the source code to be tested (Yes I know it's bad, but it is an incentive for me to keep maintaining my test code)
I'd like t开发者_如何学编程o strip the test methods from the code, build the binary and deploy.
Thanks
No, I don't know how you can do that, but I could tell you why you might not want to use this approach in the first place.
- You might be able to strip out the tests, but what about all the imports that reference test libraries?
- What about any private methods that the test might be calling? They won't be marked with
@Test
. - Why go through all this trouble in the first place? Every IDE has tools for automatically generating a test class and shortcuts for switching between them.
- what if the test annotation was accidentally applied to one of your class methods?
- What if one of your class methods accidentally calls a test method?
These are just some of the reasons I can think of... why no just avoid the problem in the first place?
There are no specific tools to do this task that I'm aware of.
You'll probably need to "take your licks" and make the changes the hard way with your favorite text editor / IDE. (And maybe this exercise will teach you to pay more heed to good practice / good style ... )
There are some tools that might help you do this (things that aim to encrypt your bytecode also tend to remove unused things).
However I would NOT advise doing that. It is good that you found a way to encourage yourself to keep the code tested (great infact!). However, as you have found out, the way you chose isn't all that good. There are many reasons to keep the test code separate from the code itself.
What I would do is (one class at a time):
1) bite the bullet and make a parallel set of classes for testing 2) move anything that has an @Test before it to the new classes 3) move over anything else that keeps the tests from compiling/running.
Then make use of a code coverage tool (I like Cobertura but there are others) to give you a visual of how much of your code is tested. Add to that the idea of writing the tests before you run the code and you should do well.
Basically this is a very formulated way of working. If you follow the regiment of coding and code coverage and then fix the places where the coverage is poor you should find it just as easy as if the test code is in the class. It is all habit - and good habits are better than bad :-)
精彩评论