Separation of JUnit classes into special test package?

后端 未结 3 1414
萌比男神i
萌比男神i 2020-12-04 06:24

I am learning the concepts of Test-Driven Development through reading the Craftsman articles (click Craftsman under By Topic) recommended in an answer to m

相关标签:
3条回答
  • 2020-12-04 07:11

    I put my test classes in the same package as what they are testing but in a different source folder or project. Organizing my test code in this fashion allows me to easily compile and package it separately so that production jar files do not contain test code. It also allows the test code to access package private fields and methods.

    0 讨论(0)
  • 2020-12-04 07:23

    I use Maven. The structure that Maven promotes is:-

    src/main/java/org/myname/project/MyClass.java
    
    src/test/java/org/myname/project/TestMyClass.java
    

    i.e. a test class with Test prepended to the name of the class under test is in a parallel directory structure to the main test.

    One advantage of having the test classes in the same package (not necessarily directory though) is you can leverage package-scope methods to inspect or inject mock test objects.

    0 讨论(0)
  • 2020-12-04 07:27

    I prefer putting the test classes into the same package as the project classes they test, but in a different physical directory, like:

    myproject/src/com/foo/Bar.java
    myproject/test/com/foo/BarTest.java
    

    In a Maven project it would look like this:

    myproject/src/main/java/com/foo/Bar.java
    myproject/src/test/java/com/foo/BarTest.java
    

    The main point in this is that my test classes can access (and test!) package-scope classes and members.

    As the above example shows, my test classes have the name of the tested class plus Test as a suffix. This helps finding them quickly - it's not very funny to try searching among a couple of hundred test classes, each of whose name starts with Test...

    Update inspired by @Ricket's comment: this way test classes (typically) show up right after their tested buddy in a project-wise alphabetic listing of class names. (Funny that I am benefiting from this day by day, without having consciously realized how...)

    Update2: A lot of developers (including myself) like Maven, but there seems to be at least as many who don't. IMHO it is very useful for "mainstream" Java projects (I would put about 90% of projects into this category... but the other 10% is still a sizeable minority). It is easy to use if one can accept the Maven conventions; however if not, it makes life a miserable struggle. Maven seems to be difficult to comprehend for many people socialized on Ant, as it apparently requires a very different way of thinking. (Myself, having never used Ant, can't compare the two.) One thing is for sure: it makes unit (and integration) testing a natural, first-class step in the process, which helps developers adopt this essential practice.

    0 讨论(0)
提交回复
热议问题