Mikayel
Mikayel

Reputation: 179

How can I use JUnit Test Runners in Maven project?

I've created quickstart maven project with dependency:

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

I have source class:

main.java.test.App

and test class:

test.java.test.AppTest

So when I try to create Result object in App class and use JUnitCore, it returns compile error, because the in junit dependency is "test". If I change or remove the scope from dependency, i can't access AppTest class from App.

Is it impossible to use Test Runners with Maven configuration?

Upvotes: 2

Views: 637

Answers (2)

John Humphreys
John Humphreys

Reputation: 39294

You should never access the Test class from the App class (and frankly, you can't).

Test code is completely separated from your main code. The test code can access your main code, but your main code can never access your test code.

This is important. Your test code is supposed to verify your real code. If main code could access test code, then you might break the very thing you're trying to verify.

Test dependencies get marked as "test" scope to ensure that Maven knows that they are not related to the main code.

Upvotes: 3

Mart&#237;n Zaragoza
Mart&#237;n Zaragoza

Reputation: 1817

You cannot access AppTest from your App class.

The junit dependency has a test scope, which means that the junit dependencies (libraries) are only used to compile and run tests, hence they are not accessible from your main code (which is App typically located in src/main).

All your test cases shall be located in src/test/java and will be run by maven when running mvn test or mvn package (or any goal that has test as an intermediate goal)

Upvotes: 2

Related Questions