JUnit is a Java software testing framework primarily built for unit testing. It also provides a standardised way to write unit tests.
It can be imported from org.junit.jupiter.api.Test
, which provides many testing methods, which can be used to define unit tests.
In order to run a JUnit tests, a testing engine is required. A common one is junit-jupiter-engine
,
Use
In order to use the JUnit framework:
- Import the following classes:
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
- The
Test
class provides java annotations which can be attached to methods.
//Defines TestMethod1 as a unit test, which will run by the test engine.
@Test
public void TestMethod1()
//Runs the method before each test / once, before all the tests.
@BeforeEach / @BeforeAll
public void setup()
//Runs the method after each test / once, after all the tests.
@AfterEach / @AfterAll
public void cleanup()
- Add asserting methods from
Assertions
class.
//Defines TestMethod1 as a unit test, which will run by the test engine.
@Test
public void TestMethod1()
{
assertEquals(expectedValue, actualValue);
assertTrue(conditionThatShouldBeTrue);
assertFalse(conditionThatShouldBeFalse);
assertArrayEquals(array, finalArray);
}