Junit 5 : How to write JUnit Test Cases?


In previous topic you learn about the JUnit setup in Java Application. In this topic you will learn about the Junit test cases writing of methods for particular java class.

Lets discuss about the test cases writing in Java application.

  • Right click on your java project -> Select New -> Junit Test Case as below.
How to write Junit Test Cases in Java application
  • After selecting the Junit Test Cases you will get below screen. Here the Jupiter option (Step 1) is for implementing the Junit Test cases with Junit 5. You can write test class name (Step 2) as CalcularTest and also select Fixture (Step 3) if initialization required for your test cases.
How to write Junit Test Case with Junit 5
  • Instead of writing the test cases, If you want to generate the Test cases for particular class then select browse (step 4) option and you will get below screen where you can search for class.
How to generate Junit test cases for particular class
  • After selecting class, click on OK button. You will get next screen with names of method where you can select methods for which you want to generate the test cases.
How to generate Junit test cases
  • After selecting methods click on Finish button, you will see a class CalculatorTest.java class added in you application with some test cases code as below.

CalculatorTest.java

JUnit Test Cases Generated
  • Now your some test cases generated with some dummy code where you can write your own logic inside of these test method by using assertion or assumption and run these test cases.

How to run Test Junit Cases?

Once you will done with the test case writing. You can follow these steps to run test cases:

  • Right click on your Java Application->select run as -> Junit
  • After executing the test cases you will see the test case result as below with red and green colors. Where green represent success and red as failure of test cases.

Junit Failed Cases

Junit some test cases failed

JUnit Success Case

Junit all success

Here I have done some changes in auto generated test cases as below and after execution showing as success as above. You can try with same or update it.

JUnit for success case

In the further topic you will learn more about the Junit 5 Annotations, Fixtures, Assertions and Assumptions in detail with examples.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s