Tuesday, June 21, 2011

Kickstart jUnit 4 example

First steps in jUnit.

import org.junit.*;
import static org.junit.Assert.*;


/**
*
* @author Georgi Mitev
*/
public class XTest {

    @Before
    // Will be performed before each test.
    public void testSetup(){
        System.out.println("Setup for test complete.");
    }

    @After
    // Will be performed after each test.
    public void testComplete() {
        System.out.println("Test complete.");
    }

    @Test
    public void test1() {
        System.out.println("Starting test 1.");
        assertTrue( true ) ;
    }

    @Test
    public void test2(){
        System.out.println("Starting test 2.");
        assertTrue( true ) ;
    }
}


We could call it easy with maven command


    • mvn test
      mvn test -Dsurefire.useFile=false - outputs more information about the errors.

  • The output of the program is:

    Running XTest
    Setup for test complete.
    Starting test 1.
    Test complete.
    Setup for test complete.
    Starting test 2.
    Test complete.
    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.062 sec

    Results :

    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

    The maven configuration for junit is
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <!--version>3.8.1</version-->
          <version>4.8.1</version>
          <scope>test</scope>
        </dependency>
        ...
      </dependencies>
    
    

    jUnit classes are placed in [project-home]\src\test\java\[junit package]\[junit class]