Compile and run test with JUnit in command line on a single Java class

Mohammad Ganji :

I have a simple problem I don't know how to solve!

I have a single Java file User.java:

import java.util.Vector;

public class User {
    private String name;
    private Vector<User> friends;

    public User(String name) {
        this.name = name;
        this.friends = new Vector<>();
    }

    public void addFriend(User newfriend) {
        friends.add(newfriend);
    }

    public boolean isFriendsWith(User friend) {
        return friends.indexOf(friend) != -1;
    }
}

and I have a simple test class UserTest.java beside this class:

import static org.junit.Assert.assertEquals;
import org.junit.Test;


public class UserTest {
    @Test
    public void evaluatesExpression() {
        User user = new User("foo");
        User user2 = new User("bar");
        user.addFriend(user2);
        assertEquals(true, user.isFriendsWith(user2));
    }
}

I want to run this test class for the User class. I'm not using IDEs like IntelliJ or Eclipse, so I want to compile the test from linux command line, but this command:

javac -cp .:"/usr/share/java/junit.jar" UserTest.java

gives me the following errors:

UserTest.java:1: error: package org.junit does not exist
import static org.junit.Assert.assertEquals;
                       ^
UserTest.java:1: error: static import only from classes and interfaces
import static org.junit.Assert.assertEquals;
^
UserTest.java:2: error: package org.junit does not exist
import org.junit.Test;
                ^
UserTest.java:6: error: cannot find symbol
    @Test
     ^
  symbol:   class Test
  location: class UserTest
UserTest.java:11: error: cannot find symbol
       assertEquals(true, user.isFriendsWith(user2));
        ^
  symbol:   method assertEquals(boolean,boolean)
  location: class UserTest
5 errors

Note: everything I have seen on Stackoverflow is about testing a single file in a project or building and testing with gradle and ..., but I don't know much about Java and I don't need to know much, I just need to know the simplest way to create and run a test for a single Java class.

Note2: I have installed junit with apt install junit and it installed junit-3-8-2 version.

Note3: I have problems when trying to compile my test class, I haven't even reached the stage where I can run the tests!

Andreas :

After quite a lot of trial and error in the comments section, the root cause was an old JUnit 3.8.2 dependency. The 3.x releases used a different namespace that was changed in 4.x to org.junit.

Therefore the classes where not found while compiling the test.

To debug such issues unzipping the jar with unzip on Linux can be helpful.

Guess you like

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