Introduction
Testing checks whether the application achieves all the requirements, serves the user with expected functionality and the correct use cases. In other words, testing is done to check the application's behavior. The entire code is divided into a few parts based on different properties. These units are called Tests.
JUnit is an open-source Regression testing framework for Java. A test in JUnit is a method or class used only for testing. These are called Test methods or Tests classes. To define a method as a test method, you can add @Test annotation before it. There are a few other annotations like @After, @Before, @Ignore, etc., in JUnit. Let’s explore what the JUnit test cases are in this article.
JUnit Test cases
JUnit provides essential features like
- Fixtures
- Test suites
- Test runners
- JUnit classes
The syntax of the JUnit test methods is as follows.
Public class JUnitSyntax {
@Annotation // Any annotation according to testing requirements
Public void method() {
// Method body
}
}The access specifiers like public, private, etc., can be given according to the code requirements, and the tester can choose any return type among all the existing types.
Let's take a look at basic test cases with code now.
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class JunitAnnotations {
@Test
public void test() {
System.out.println("Inside @Test annotation method")
}
@After
public void after() {
System.out.println("Inside @After annotation method");
}
@Before
public void before() {
System.out.println("Inside @Before annotation method");
}
}We used the annotations @Test, @After, @Before in the above code to create the test methods. It gives us the following output.
Output
Inside @Before annotation method
Inside @Test annotation method
Inside @After annotation method
- The test method before() with @Before annotation gets executed before all the other methods.
- The method test() with @Test gets executed and prints the output.
- After all the methods are executed, the @After annotation executes the method after().



