1.

How will you write a simple JUnit test case?

Answer»

Let us understand how to WRITE a simple JUnit Test Case using an example. Consider a Calculator class that has a method that adds 2 numbers:

public class Calculator { public INT add(int num1, int num2) { return num1 + num2; }}

Let us write a test case in JUnit 5 to this method under a class named CalculatorTest.

import static org.junit.jupiter.api.Assertions.assertEquals;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.DISPLAYNAME;import org.junit.jupiter.api.RepeatedTest;import org.junit.jupiter.api.Test;public class CalculatorTest { Calculator calcObject; @BeforeEach void setUp() { calcObject = new Calculator(); } @Test @DisplayName("Add 2 numbers") void addTest() { assertEquals(15, calcObject.add(10, 5)); } @RepeatedTest(5) @DisplayName("Adding a number with zero to return the same number") void testAddWithZero() { assertEquals(15, calcObject.add(0, 15)); }}

From the above example, we can see that:

  • @BeforeEach annotated method runs before each test case. In JUnit 4, this annotation was @Before.
  • @Test annotation indicates that the method is a test method.
  • @DisplayName is used for defining the test name displayed to the user.
  • assertEquals() method is used for validating whether the expected and actual values are equal.
  • @RepeatedTest annotation indicates that the test method will be run 5 times.


Discussion

No Comment Found