How to use scope "test" and junit correctly with maven and eclipse

Doena :

I am trying to understand what I am doing wrong with junit-tests in Maven with eclipse. Mainly I have been just following this "getting started guide" for Maven: https://spring.io/guides/gs/maven/

But for me it is not completely working like that when it comes to junit.

To follow the exact folder-structure from the example I have named my packages under src in eclipse: main.java.hello test.java.hello

My test class GreeterTest.java is in the package test.java.hello and has this content:

package test.java.hello;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.*;

import org.junit.Test;

import main.java.hello.Greeter;

public class GreeterTest {

    private Greeter greeter = new Greeter();

    @Test
    public void greeterSaysHello() {
        assertThat(greeter.sayHello(), containsString("Hello"));
    }

}

In my pom.xml you find the dependency:

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

Unfortunately eclipse sais "the import org.junit cannot be resolved." If change the scope of the dependency from test to compile I do not get this error message, but that would be not the way how the scope is intended to be used, is it?

What do I need to change that also eclipse understands, that this class is a test-class and therefore all dependencies are actually available?

Best,Nils

davedupplaw :

The issue appears to be related to where Eclipse thinks your source tree starts. You have put your code in src/main/java/hello and src/main/test/hello but Eclipse thinks the source tree starts at src. So it thinks the other folders are packages and has given your classes package names like main.java.hello.Greeter.

The quickest way to fix this is to run on the command line:

mvn eclipse:eclipse

which uses maven to fix your eclipse projects. It will automatically set the source root to be the correct values. When it completes, right click on the project and select Refresh to see the updated project.

To fix this manually, you can right click on the project and choose Build Path > Configure Build Path and, in the Source tab on the right, ensure that the entire src/main/java (right up to java!) is included as the source folder. Do this by clicking Add Folder and selecting java in the tree under src - main. Do the same for src/main/test. Usually maven projects include src/main/resources as a source folder too.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=111742&siteId=1