Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
/usr/share/java/junit.jar links to the latest junit3 version, while /usr/share/java/junit4.jar links to the latest junit4 version. –  daniel kullmann Apr 11 '12 at 7:12

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.