Labs SD > Ferramentas

JUnit

O JUnit é uma biblioteca Java para escrever testes ao código.

O Maven já vem preparado para executar testes unitários, na fase test do ciclo de vida,
mas é necessário adicionar a dependência para a biblioteca JUnit:

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

As classes de testes são aquelas cujo nome, por omissão, termina com Test. Devem ser arrumadas na pasta src/test/java do projeto.

Uma classe de testes tem a seguinte estrutura:

package example.test;

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

/** Test suite */
public class ExampleTest {

    // static members

    // one-time initialization and clean-up
    @BeforeClass
    public static void oneTimeSetUp() {
        // runs once before all tests in the suite
    }

    @AfterClass
    public static void oneTimeTearDown() {
        // runs once after all tests in the suite
    }

    // members

    // initialization and clean-up for each test
    @Before
    public void setUp() {
        // runs before each test
    }

    @After
    public void tearDown() {
        // runs after each test
    }

    // tests
    @Test
    public void test() {
        // do something ...

        // assertEquals(expected, actual);
        // if the assert fails, the test fails
    }
}

No JUnit 4 são utilizadas anotações para definir qual o papel dos métodos.

As funções de assert permitem verificar o resultado esperado de um teste:

O plug-in de Maven que corre os testes chama-se Surefire.
Os exemplos seguintes mostram como correr os testes e como controlar quais os testes a executar.

// to compile and execute all tests
$ mvn test

// to execute only a specific test class
$ mvn test -Dtest=PingIT

// to execute only a specific test
$ mvn test -Dtest=PingIT#testPing

// you can also use wildcards (the example below will match classes starting with P)
$ mvn test -Dtest=P*

// to skip integration tests
$ mvn package -Dtest.skip=true
Para mais informação sobre JUnit, consultar:

 

Testes com exceções

Para implementar testes de exceções existem duas abordagens: com expected na anotação @Test ou não.

    ...

    @Test(expected=ExampleException.class)
    public void testExceptionWithAnnotation() throws Exception {
        // ... code that must throw an exception

        // JUnit expects the exception declared in the annotation
        // if it is not thrown, the test fails
    }

    ...

    @Test
    public void testExceptionWithoutAnnotation() throws Exception {
        try {
            // ... code that must throw an exception

            fail();
        } catch (Exception e) {
            // check message of expected exception, etc
        }
    }

    ...

© Docentes de Sistemas Distribuídos, Dep. Eng. Informática, Técnico Lisboa