Question

C# developer here, working through basic Java examples. JUnit test cases appear to be packaged with the class under test in the tutorials I've seen. Is that right? In C# we create a new Test project - surely in Java the common pattern is similar?

Was it helpful?

Solution

As I said in my comment, these days the defacto standard is the Maven structure where tests are in the same package (Namespace in C#) but under a different source roots (src/main/java and src/test/java respectively), though you are free to put the tests wherever you want.

There are however, some benefits to having the tests in the same package because the Java visibility rules mean the test has access to both protected and package private methods, allowing it to be that little bit more interment with the class under test (this isn't something you should rely on all the time but it's useful now and again).

Anyway, I digress, the structure would look something like this:

my-project
+ src
  + main
  | + java
  |   + com
  |     + company
  |       + MyNewClass
  + test
    + java
      + com
        + company
          + MyNewClassTest

In the Java world it's the norm to have an external build tool, Maven being the current flavor of the month. It's supported by most IDEs, which will recognize this structure when they're sync'd with the Maven project file (pom).

That doesn't mean you can't use this structure if you don't used Maven, you'll just have to manually add additional source roots to the IDE project/module.

In IntelliJ, you do this in the Project Settings -> Modules on the Sources tab. You do something similar in Eclipse, but not sure the exact path (sure somebody will add how in the comments :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top