Home
Categories
Dictionary
Glossary
Download
Project Details
Changes Log
What Links Here
FAQ
License

JUnit concepts



This article explains several key concepts about the JUnit framework, which is the Unit tests framework used by the protoFramework project.

Test class architecture

Test class declaration

A JUnit test is a class which name ends with the Test string (for example: MapsDependencyTest is a valid test class name), and with tests methods annotated with the @Test annotation.

For example for a very simple Test class which tests nothing:
      public class MyTest {
      @Test
      public void aTestMethod {
      }
      }

Test assertions

Assertions are used to check if a result is consistent with an expected value. Some kinds of built-in JUnit assertions are:
  • value equality: for example assertEquals("The value is not equal to expected", 2, value). It is possible to check decimal values by providing an accepted delta, for example: assertEquals("The value is not equal to expected", 2.3f, value, 0.1f)
  • Boolean value check. For true: assertTrue("The value should be true", b). For false: assertFalse("The value should be false", b)
  • Null check. For null: assertNull("The value should be null", o). For not null: assertNotNull("The value should not be null", o)

Errors and fails

There is a difference between a Unit Test fail and an error:
  • There is an error if there is an unrecovered exception thrown in a test
  • There is a fail if there is a not fullfilled assertion in a test


For example this test case will result in an error:
      @Test
      public void aTestMethod {
      int i = 1 / 0;
      }
And this test case will result in a fail:
      @Test
      public void aTestMethod {
      assertTrue("Value must be true", false);
      }

Test cases execution

JUnit executes the test classes by:
  • Create by reflection each test class (which are those with the name ending with Test)
  • Execute the @BeforeClass method
  • For each method annotated with @Test:
    • Create by reflection an instance of the test class
    • Execute the @Before method
    • Execute the test case method
    • Execute the @After method
  • Execute the @AfterClass method
Note that beginning with Java 7, there is no way to control the order on which the test cases will be executed. There is however a way to control this order in J661 Unit tests.

Also the fact that there is an instanciation of the test class for each test case means that if you want to keep values and states between several test cases, you will need to set static fields for the class to be able to keep them between several test methods call. The affection of these values can for example be performed in the @BeforeClass method.

See also


Categories: development

Copyright 2017-2020 Dassault Aviation. All Rights Reserved. Documentation and source under the LGPL v3 licence