Search code examples
javajunitpowermockito

Should we create Java source code and Junit test as different project in java like they do in .Net?


In Java, I have seen the practice of having test and source in the same project inside different packages. But now someone asked me to make Java source code as a different project and Take test out of the main project and make it a separate Test project like in .net and give the reference of that source jar in the project.

See Following is the practice in general we follow

src>>main>>java>>com>>foo>>Sample.java

test>>main>>java>>com>>foo>>SampleTest.java

But now someone asked me to create a project

src>>main>>java>>com>>foo>>Sample.java

as one project and then make Test like a Java project give reference of the above jar into your test project(add that jar into libs or add a dependency into your build file) to execute test cases.

test>>main>>java>>com>>foo>>SampleTest.java

Do you think that is a feasible solution?

Should we follow such kind of practice.?


Solution

  • Since you mention Java, it is a usual practice for Java based projects to have Junit tests in the same project(maven/gradle). Your source and test code structure would look like this:

    src
    │  
    ── main
         └── java
             └── com
                  └── foo
    │                 ├──Sample.java
    │     
    │       
    └── test
         └── java
              └── com
                   └── foo
                       └── SampleTest.java
    

    With source and junit in the same project, you will be able to relate to the code and unit tests much better. This approach allows the tests to access to all the public and package visible methods of the classes under test.

    This is also part of a standard maven/gradle directory layout where the project is the same but folder is separate.

    A common set of integration or functional tests can exist in a separate project depending on the requirement.

    You can also refer to Junit FAQ which talks about organizing tests.

    Keep it simple, you could get started by keeping unit tests in same project and think of separating it if really needed.