Учебники

4) JUnit Аннотации и API

Что такое аннотации JUnit?

JUNIT ANNOTATIONS — это особая форма синтаксических метаданных, которые могут быть добавлены в исходный код Java для лучшей читаемости и структуры кода. Переменные, параметры, пакеты, методы и классы могут быть аннотированы. Аннотации были введены в Junit4, что делает код Java более читабельным и простым. Это большая разница между Junit3 и Junit4 в том, что Junit4 основан на аннотациях.

Зная аннотации в Junit5, можно легко выучить и реализовать тест JUnit. Ниже приведен список важных и часто используемых аннотаций:

S.No. Аннотации Описание
1. @Тестовое задание Эта аннотация является заменой org.junit.TestCase, которая указывает, что открытый метод void, к которому он присоединен, может быть выполнен как тестовый пример.
2. @Перед Эта аннотация используется, если вы хотите выполнить некоторые операторы, такие как предварительные условия, перед каждым тестовым примером.
3. @BeforeClass Эта аннотация используется, если вы хотите выполнить некоторые операторы перед тем, как все тестовые примеры, например тестовое соединение, должны быть выполнены перед всеми тестовыми примерами.
4. @После Эту аннотацию можно использовать, если вы хотите выполнять некоторые операторы после каждого теста, например, для сброса переменных, удаления временных файлов, переменных и т. Д.
5. @После урока Эту аннотацию можно использовать, если вы хотите выполнить некоторые операторы после всех тестовых случаев, например, для освобождения ресурсов после выполнения всех тестовых случаев.
6. @Ignores Эту аннотацию можно использовать, если вы хотите игнорировать некоторые операторы во время выполнения теста, например, для отключения некоторых тестовых случаев во время выполнения теста.
7. @Test (тайм-аут = 500) Эту аннотацию можно использовать, если вы хотите установить некоторое время ожидания во время выполнения теста, например, если вы работаете по некоторому SLA (Соглашение об уровне обслуживания), и тесты должны быть завершены в течение определенного времени.
8. @Test (ожидаемый = IllegalArgumentException.class) Эту аннотацию можно использовать, если вы хотите обработать какое-то исключение во время выполнения теста. Например, если вы хотите проверить, вызывает ли конкретный метод указанное исключение или нет.

В этом уроке вы узнаете

Пример аннотаций JUnit

Давайте создадим класс, охватывающий важные аннотации JUnit с помощью простых операторов print, и выполним его с помощью класса тестового прогона:

Step 1) Consider below java class having various methods which are attached to above-listed annotations:

JunitAnnotationsExample.java

package guru99.junit;		

import static org.junit.Assert.assertEquals;				
import static org.junit.Assert.assertFalse;				

import java.util.ArrayList;		

import org.junit.After;		
import org.junit.AfterClass;		
import org.junit.Before;		
import org.junit.BeforeClass;		
import org.junit.Ignore;		
import org.junit.Test;		

public class JunitAnnotationsExample {				

    private ArrayList<String> list;					

    @BeforeClass		
    public static void m1() {							
        System.out.println("Using @BeforeClass , executed before all test cases ");					
    }		

    @Before		
    public void m2() {					
        list = new ArrayList<String>();					
        System.out.println("Using @Before annotations ,executed before each test cases ");					
    }		

    @AfterClass		
    public static void m3() {							
        System.out.println("Using @AfterClass ,executed after all test cases");					
    }		

    @After		
    public void m4() {					
        list.clear();			
        System.out.println("Using @After ,executed after each test cases");					
    }		

    @Test		
    public void m5() {					
        list.add("test");					
        assertFalse(list.isEmpty());			
        assertEquals(1, list.size());			
    }		

    @Ignore		
    public void m6() {					
        System.out.println("Using @Ignore , this execution is ignored");					
    }		

    @Test(timeout = 10)			
    public void m7() {					
        System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case");					
    }		

    @Test(expected = NoSuchMethodException.class)					
    public void m8() {					
        System.out.println("Using @Test(expected) ,it will check for specified exception during its execution");					

    }		

}		

Step 2) let’s create a test runner class to execute above test:

TestRunner.java

package guru99.junit;		

import org.junit.runner.JUnitCore;		
import org.junit.runner.Result;		
import org.junit.runner.notification.Failure;		

public class TestRunner {				
			public static void main(String[] args) {									
      Result result = JUnitCore.runClasses(JunitAnnotationsExample.class);					
			for (Failure failure : result.getFailures()) {							
         System.out.println(failure.toString());					
      }		
      System.out.println("Result=="+result.wasSuccessful());							
   }		
}      	

Expected Result

  • All the test cases will be executed one by one, and all print statement can be seen on a console.
  • As discussed in above table @Before, @BeforeClass [ method m1() and m2() ] will be executed before each and before all test cases respectively.
  • In the same way @after,@afterClass (method m3() and m4()) will be executed after each and after all test cases respectively. @ignore (method m6())will be treated as ignoring the test.

Let’s analyse test cases used in above java class in detail:

  1. Consider method m5() as given below :
	@Test		
    public void m5() {					
        list.add("test");					
        assertFalse(list.isEmpty());			
        assertEquals(1, list.size());			
    }		

In above method as you are adding a string in the variable «list» so

  • list.isEmpty() will return false.
  • assertFalse(list.isEmpty()) must return true.
  • As a result, the test case will pass.

As you have added only one string in the list, so the size is one.

  • list.size() must return int value as «1» .
  • So assertEquals(1, list.size()) must return true.
  • As a result, the test case will pass.
  1. Consider method m7() as given below :
@Test(timeout = 10)		
    public void m7() {					
        System.out.println("Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case");					
    }		

As discussed above @Test(timeout = 10)annotation is used to enforce timeout in the test case.

  1. Consider method m8() as given below :
@Test(expected = NoSuchMethodException.class)				
    public void m8() {					
        System.out.println("Using @Test(expected) ,it will check for specified exception during its execution");					
    
    }		

As discussed above @Test(expected) will check for specified exception during its execution so method m8() will throw «No Such Method Exception.» As a result, the test will be executed with an exception.

As all test cases are passed, this results in a successful test execution.

Actual Result

As there are three test cases in above example, all test cases will be executed one by one. See output below:

JUnit Аннотации и API

See below print statements which can be seen on console:

Using @BeforeClass , executed before all test cases

Using @Before annotations, executed before each test cases

Using @After, executed after each test cases

Using @Before annotations, executed before each test cases

Using @Test(timeout),it can be used to enforce timeout in JUnit4 test case

Using @After, executed after each test cases

Using @Before annotations, executed before each test cases

Using @Test(expected) ,it will check for specified exception during its execution

Using @After, executed after each test cases

Using @AfterClass, executed after all test cases

JUnit Assert Class

This class provides a bunch of assertion methods useful in writing a test case. If all assert statements are passed, test results are successful. If any assert statement fails, test results are failed.

As you seen earlier, below table describes important Assert methods and description:

S.No. Method Description
1. void assertEquals(boolean expected, boolean actual) It checks whether two values are equals similar to equals method of Object class
2. void assertFalse(boolean condition) functionality is to check that a condition is false.
3. void assertNotNull(Object object) «assertNotNull» functionality is to check that an object is not null.
4. void assertNull(Object object) «assertNull» functionality is to check that an object is null.
5. void assertTrue(boolean condition) «assertTrue» functionality is to check that a condition is true.
6. void fail() If you want to throw any assertion error, you have fail() that always results in a fail verdict.
7. void assertSame([String message] «assertSame» functionality is to check that the two objects refer to the same object.
8. void assertNotSame([String message] «assertNotSame» functionality is to check that the two objects do not refer to the same object.

JUnit Test Cases Class

To run multiple test, TestCase class is available in org.junit.TestCase packages. Annotation @Test tells JUnit that this public void method (Test Case here) to which it is attached can be run as a test case.

Below table shows some important methods available in org.junit.TestCase class:

S.No. Method Description
1. int countTestCases() This method is used to count how many number of test cases executed by run(TestResult tr) method.
2. TestResult createResult() This method is used to create a TestResult object.
3. String getName() This method returns a string which is nothing but a TestCase.
4. TestResult run() This method is used to execute a test which returns a TestResult object
5. void run(TestResult result) This method is used to execute a test having a TestResult object which doesn’t returns anything.
6. void setName(String name) This method is used to set a name of a TestCase.
7. void setUp() This method is used to write resource association code. e.g. Create a database connection.
8. void tearDown() This method is used to write resource release code. e.g. Release database connection after performing transaction operation.

JUnit TestResult Class

Когда вы выполняете тест, он возвращает результат (в форме объекта TestResult ). Этот объект TestResult может использоваться для анализа результирующего объекта. Этот результат теста может быть либо неудачным, либо успешным. Ниже приведена таблица важных методов, используемых в классе org.junit.TestResult:

S.No. метод Описание
1. void addError (Тестовый тест, Throwable t) Этот метод используется, если вам требуется добавить ошибку в тест.
2. void addFailure (Тестовый тест, AssertionFailedError t) Этот метод используется, если требуется добавить ошибку в список ошибок.
3. void endTest (Тестовый тест) Этот метод используется для уведомления о том, что тест выполнен (завершен)
4. int errorCount () Этот метод используется для получения ошибки, обнаруженной во время выполнения теста.
5. Перечисление <TestFailure> ошибки () Этот метод просто возвращает коллекцию (перечисление здесь) ошибок.
6. int failureCount() This method is used to get the count of errors detected during test execution.
7. void run(TestCase test) This method is used to execute a test case.
8. int runCount() This method simply counts the executed test.
9. void startTest(Test test) This method is used to notify that a test is started.
10. void stop() This method is used to test run to be stopped.

JUnit Test Suite Class

If you want to execute multiple tests in a specified order, it can be done by combining all the tests in one place. This place is called as the test suites.

See below table for important methods used in org.junit.TestSuite class:

S.No. Method Description
1. void addTest(Test test) This method is used if you want to add a test to the suite.
2. void addTestSuite(Class<? extends TestCase> testClass) This method is used if you want to specify the class while adding a test to the suite.
3. int countTestCases() This method is used if you want to count the number of test cases.
4. String getName() This method is used to get the name of the test suite.
5. void run(TestResult result) This method is used to execute a test and collect test result in TestResult object.
6. void setName(String name) This method is used to set the name of TestSuite.
7. Test testAt(int index) This method is used if you want to return the test at given index.
8. int testCount() This method is used if you want to return a number of tests in the Suite.
9. static Test warning(String message) This method returns a test which will fail and log a warning message.

Summary:

  • JUnit предоставляет переносимый API, который предоставляет все важные классы и аннотации, полезные при написании модульного теста.
  • Классы, которые очень полезны при написании теста
    • org.junit.Assert
    • org.junit.TestCase
    • org.junit.TestResult
    • org.junit.TestSuite
  • список важных и часто используемых аннотаций

    @Перед

    @BeforeClass

    @После

    @После урока

    @Тестовое задание

    @Ignore