Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create method that could be used only for tests

Are the any ways to create method/contractor that could be used only in Junit ( test purpose only ) ?

Maybe there is an annotation?


1 Answers

For methods that are only used for testing... why not make them part of the actual test-code? At least in build-systems such as Maven, test code is not included in packaged jars, and is only distributed as part of the sources. In that sense, it cannot be called from normal classes, since it is simply not included in the final .jar (or .war).

I very frequently write such methods to make my test-code more maintainable.

To clarify:

src/
  main/
    java/
      my/package/
        MyClass.java <-- leave necessary protected accessors here
  test/
    java/
      my/package/
        MyClassTest.java <-- implement test-code here

And in MyClassTest...

public class MyClassTest {

   ...

   private static Foo doSomethingCoolButTesty(MyClass instance) {
       // access protected or package-private MyClass code here 
   }
}

MyClassTest.doSomethingCoolButTesty will be kept separate from the main code, and will obviously only be available to test code. Yes, it is somewhat uglier than including it as a method of the main code, but I find a fair price to pay.

like image 61
tucuxi Avatar answered Oct 19 '25 04:10

tucuxi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!