JUnit - Основные примеры аннотаций

JUnit - основные примеры аннотаций

Вот несколько основных аннотаций JUnit, которые вам следует понять:

  1. @BeforeClass - выполняется один раз перед любым из тестовых методов в классеpublic static void

  2. @AfterClass - запускается один раз после выполнения всех тестов в классе,public static void

  3. @Before - запускать перед @Test,public void

  4. @After - Запуск после @Test,public void

  5. @Test - это метод тестирования для запуска,public void

P.S Tested with JUnit 4.12

BasicAnnotationTest.java

package com.example;

import org.junit.*;

public class BasicAnnotationTest {

    // Run once, e.g. Database connection, connection pool
    @BeforeClass
    public static void runOnceBeforeClass() {
        System.out.println("@BeforeClass - runOnceBeforeClass");
    }

    // Run once, e.g close connection, cleanup
    @AfterClass
    public static void runOnceAfterClass() {
        System.out.println("@AfterClass - runOnceAfterClass");
    }

    // Should rename to @BeforeTestMethod
    // e.g. Creating an similar object and share for all @Test
    @Before
    public void runBeforeTestMethod() {
        System.out.println("@Before - runBeforeTestMethod");
    }

    // Should rename to @AfterTestMethod
    @After
    public void runAfterTestMethod() {
        System.out.println("@After - runAfterTestMethod");
    }

    @Test
    public void test_method_1() {
        System.out.println("@Test - test_method_1");
    }

    @Test
    public void test_method_2() {
        System.out.println("@Test - test_method_2");
    }

}

Выход

@BeforeClass - runOnceBeforeClass

@Before - runBeforeTestMethod
@Test - test_method_1
@After - runAfterTestMethod

@Before - runBeforeTestMethod
@Test - test_method_2
@After - runAfterTestMethod

@AfterClass - runOnceAfterClass

Рекомендации