JUnit Tutorial

JUnit Tutorial | Testing Framework for Java JUnit tutorial

provides basic and advanced concepts of unit testing in java with examples. Our junit tutorial is designed for beginners and professionals.

Supported Java Versions

JUnit 5.x requires at least Java 8 at runtime. However, you can still test code that has been compiled with previous versions of the JDK.

What is JUnit test?

JUnit test is a method contained in a class which is only used for testing. This is called a Test class. … You use an assert method, provided by JUnit or another assert framework, to check an expected result versus the actual result.

JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage

Installing in Local Maven Repository

All modules can be installed with the Gradle Wrapper in a local Maven repository for consumption in other projects via the following command.

JUnit test case example

Below example is minimum requirements for writing a test in JUnit Jupiter.

JUnit test Annotations

Following annotations that can be used while writing the JUnit test cases based on the Junit 5.x framework version.

  • @Test
  • @ParameterizedTest
  • @RepeatedTest
  • @TestFactory
  • @TestTemplate
  • @TestMethodOrder
  • @TestInstance
  • @DisplayName
  • @DisplayNameGeneration
  • @BeforeEach
  • @AfterEach
  • @BeforeAll
  • @AfterAll
  • @Nested
  • @Tag
  • @Disabled
  • @Timeout
  • @ExtendWith
  • @RegisterExtension

Methods of Assert class

Below are the common methods of Assert class:

  1. void assertEquals(boolean expected,boolean actual)
  2. void assertTrue(boolean condition)
  3. void assertFalse(boolean condition)
  4. void assertNull(Object obj)
  5. void assertNotNull(Object obj)

How to write junit test cases

Here we are going to write the JUnit test case for the Java class for the better the understanding.

Java Program Code

JUnit Test Example

Output:

Another JUnit test example for custom JUnit rules.

 

If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.

Recommended Posts:


Editorial Staff

Editorial Staff at FreeWebMentor is a team of professional developers.