Java - Junit - Interview Questions and Answers on Annotations

Q1.  What are the annotations used in Junit  with Junit4 ?

Ans. @Test

The Test annotation indicates that the public void method to which it is attached can be run as a test case.


The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.


The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class.


The After annotation indicates that this method gets executed after execution of each test.


The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the set-up. 


The Ignore annotation can be used when you want temporarily disable the execution of a specific test.

Q2.  How to create a Junit to make sure that the tested method throws an exception ?

Ans. Using annotation Test with the argument as expected exception.

@Test (expected = Exception.class)

Q3.  How should we ignore or avoid executing set of tests ?

Ans. We can remove @Test from the respective test so as to avoid its execution. Alternatively we can put @Ignore annotation on the Junit file if we want to ignore all tests in a particular file.

Q4.  How can we test methods individually which are not visible or declared private ?

Ans. We can either increase their visibility and mark them with annotation @VisibleForTesting or can use reflection to individually test those methods.

Q5.  Which of the following annotation is used to avoid executing Junits ?

 a. @explicit
 b. @ignore
 c. @avoid
 d. @NoTest

Ans. @ignore