Testing, Debugging, and Verification TDA567/DIT082, LP2, HT2017

JUnit

JUnit

JUnit is a testing tool for Java. It helps you write down, structure, and run your test cases. JUnit is not a magical tool that tries to come up with test cases for you automatically!

See JUnit's home-page, in particular the Getting Started page.

Install and Use

Installing JUnit is very easy.

  1. Get JUnit by either:
    • downloading the distribution from www.junit.org
    • in case you run Linux, check whether your distribution offers JUnit (Ubunt does), and install it
    In either case, make sure you use JUnit4 or higher.
    No further installation is needed!
  2. When writing a test class, import the following:
    import org.junit.*;
    import static org.junit.Assert.*;
    

    To mark a method (for instance testMethodName) as a test case annotate it with @Test, e.g.:

    @Test public void testMethodName() { ... }

    To decide whether a test was successful, the test method makes the following call:

    assertTrue(condition);
    
    where condition is a condition for the test being successful.
  3. For compiling and running your tests, the java classpath must include the .jar file of JUnit (like junit-4.x.jar, or junit4.jar, or alike). You can achieve that through setting the classpath environment variable, or by giving the classpath as an option (-cp) to javac and java.
    • under Windows:
      • compile test:
        javac -cp .;pathToAndIncludingJunitJarFile YourTestClass.java
      • To run all methods annotated with @Test in a class:
        java -cp .;pathToAndIncludingJunitJarFile org.junit.runner.JUnitCore YourTestClass
    • under Linux:
      • compile test:
        javac -cp .:pathToAndIncludingJunitJarFile YourTestClass.java
      • To run all methods annotated with @Test in a class:
        java -cp .:pathToAndIncludingJunitJarFile org.junit.runner.JUnitCore YourTestClass
    where pathToAndIncludingJunitJarFile and YourTestClass are named accordingly.
You can read more about using JUnit in the JUnit Cookbook.




Home | Course | Schedule | Exam | Exercises | Labs | Evaluation | Tools Srinivas Pinisetty, Sep 22, 2017