How to install/use JUnit?
I have installed JUnit on my Ubuntu 11.04
sudo apt-get install junit
Then created a test file like:
import org.junit.*;
public class TestBasicLinkedList {
@Test public void testCanAdd(String[] args) {
BasicLinkedList<Integer> list = new BasicLinkedList();
list.add(new BasicListNode<Integer>(1));
assertTrue(list.size() == 1);
assertTrue(list.getFirst().getElement().equals(1));
}
}
Then tried running in terminal
java org.junit.runner.JUnitCore TestBasicLinkedList.java
Got:
Exception in thread "main" java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
Caused by: java.lang.ClassNotFoundException: org.junit.runner.JUnitCore
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: org.junit.runner.JUnitCore. Program will exit.
How do I use JUnit? Is there a better shorter way of using it than the long command java org.junit.runner.JUnitCore TestBasicLinkedList.java
? Perhaps something like junit *.Tests.java
maybe?
Solution 1:
To get you up and running, this is a basic test case:
import junit.framework.TestCase;
public class TestBasicLinkedList extends TestCase {
public void testTrue() {
assertTrue(true);
}
}
The test class should extend TestCase, and test methods should start with "test", accept no arguments and return void.
To compile:
javac -cp /usr/share/java/junit4.jar TestBasicLinkedList.java
To run:
java -cp /usr/share/java/junit4.jar:. org.junit.runner.JUnitCore TestBasicLinkedList
This is for JUnit 4; JUnit 3 uses different classes for executing tests (try junit.textui.TestRunner).
Solution 2:
In general, JUnit (just like any Java library) needs to be on your classpath. I don't know where exactly Ubuntu stores junitX.jar, but you probably want something like this:
java -cp .:/usr/share/java/junit4-4.10.jar TestBasicLinkedList
You'll need to compile TestBasicLinkedList
first.