Top 20 JUnit Interview Questions with Answers [Java Unit Testing]

Hello guys, if you are preparing for a Java programming interview and looking for some JUnit and testing interview questions then you have come to the right place. Earlier, I have shared the best JUnit and TDD courses and books, and, today, I am going to share some JUnit interview questions for Java developers. There is no doubt that JUnit is the defacto standard framework for writing unit tests in Java and every professional developer must be familiar with JUnit. Not long ago, you can clear Java interviews without writing a single line of code, forget about tests but not many more. More and more companies are including coding tests and take-home tests where you need to build solutions and write code with tests on their hiring process. 


If you can't write a Unit test then it's a big problem and that's why it's very very important that you know about JUnit and how to use JUnit + Mockito for writing unit tests. To be honest, Unit tests are the single most important thing which separates an amateur developer from a professional developer. 

When you write professional code as part of your job, you must write a unit test so that you can test your logic confidently and repeatedly, Writing Unit test is not only the best coding practice and make you a better developer but also it leaves a good impression on the interviewer or whoever review your code. If you are a team lead, you shouldn't approve a GitHub pull request if there is no unit test. 

Coming back to these JUnit interview questions they are good to recap essential JUnit and testing concepts as well as to explore the JUnit arena if you are a beginner. Btw, if you are new to the Java testing arena then I also recommend you to join Learn Java Unit Testing with JUnit & Mockito in the 30 Steps course by Ranga Karnam on Udemy. It's a great course to learn unit testing basics with JUnit and Mockito, two of the leading libraries for testing Java applications. 




20+ JUnit [Java Unit Testing] Interview Questions with Answers

Without wasting any more of your time, here is my list of frequently asked JUnit interview questions for Java programmers. These interview questions are quite popular on both telephonic and face-to-face interviews as they touch many of the crucial JUnit concepts and unit testing fundamentals. 

1. What is JUnit?
JUnit is a unit testing framework for the Java application. It allows you to unit test your code at the method level. You can also use JUnit for test-driven development e.g. first writing test and then writing actual code. Most of the Java IDE like Eclipse, Netbeans and IntelliJ Idea provides out-of-box JUnit integration for TDD. Even build tools like Maven, Ant, and Gradle can run the JUnit test at compile and built time.


2. What is the difference between JUnit 3.X and JUnit 4.x?
The main difference between JUnit 3 and JUnit 4 is annotation. Earlier you need to start your method name as testXXX() but from JUnit 4.0 onwards you can use @Test annotation, which removes this dependency to start your Junit test methods as a test.


3. What do @Before and @After annotation does in JUnit 4?
@Before and @After annotation is used for setup and cleanup jobs. They are actually a replacement of the setUp() and tearDown() method of JUnit 3.X. Remember, a method annotated with @Before will be called before calling a test method and @After will be called after executing the test method. 

So if you have 5 test methods in one JUnit test class, they will be called five times. You will be glad to know that JUnit 5 has renamed @Before to @After to @BeforeEach and @AfterEach to make it more readable. 


4. What is the difference between @Before and @BeforeClass annotation in JUnit?
@Before is called per test method while @BeforeClass is called per-test-class level. Also, static methods are annotated with @BeforeClass and you can use them to initialize shared resources e.g. which should be shared by every instance of JUnit class like Database connection.

And, if you are new to unit testing and just looking for good online training courses to learn unit testing in Java then I highly recommend you check out Learn Java Unit Testing with JUnit 5 in the 20 Steps course by Ranga Rao on Udemy. It's a good course to learn JUnit 5 in easy-to-follow steps. 

Top 20 JUnit Interview Questions with Answers for Java Programmers




5. How does JUnit achieve the isolation of tests?
JUnit creates a separate instance of the test class for calling test methods. For example, if your test class contains 5 tets then JUnit will create 5 instances of the test class for executing those test methods. That's why constructor is called before executing @Test methods. In JUnit 3.X, It used to first create instances and then call the methods but in JUnit 4.1, it first creates an instance and then calls them the method and then goes on to create the second method. This way, it keeps one test isolated from the other.


6. What is difference between setUp() and tearDown() method?
They are methods from JUnit 3.X which is replaced by @Before and @After annotated method. They are used for setting up resources before the test method and for doing clean-up after-test methods.


7. How do you check if a test method throws Exception in JUnit?
In JUnit 4, you can use @Test annotation with an expected parameter to specify the exception thrown by a test method. If the test method throws that Exception then JUnit will mark your test passed, otherwise, it will mark them as failed. 

For example, if you want to verify your method should throw IllegalArgumentException if the given parameter is bad then you can annotate your test method as @Test(expected = IllegalArgumentException.class). In earlier versions e.g. on JUnit 3.X, you could have used catch block to verify if the method under test throws a particular exception or not.


8. How do you ignore certain test methods in the JUnit Test class?
Well, from JUnit 4 onwards you can use @Ignore annotation to instruct JUnit runtime to not execute any particular test or disable any test as shown in this JUnit ignore example. You can also use this method for annotating unimplemented test methods. Btw, you should use @Ignore only temporarily and remove it as soon as possible by either implementing the test methods or removing it if not required.


9. Can you test a Java method for timeout using JUnit?
Yes, JUnit provides a timeout parameter to @Test annotation which can be used to instruct JUnit to pass or fail a test method based upon execution time. For example, a JUnit test method annotated with @Test(timeout= 50) will be failed it doesn't complete in 50 milliseconds (timeout is specified in millisecond). This is the standard way to verify the SLA of a Java method. 

If you want to learn more about timeouts and other advanced JUnit features then I highly recommend you to join Java Unit Testing with JUnit 5, a text-based, interactive course on Educative. You can practice unit testing right on your browser without any additional setup. 

best course to learn JUnit 5 for beginners



10. What are some best practices you follow while writing code to make it more testable?
Here are some of the best practices you can follow to make your code more testable :
1) Use interface instead of concrete class, this allows the tester to replace actual class with Mock or Stub for testing purpose.
2) Use Dependency injection, it makes it easy to test individual parts and supply dependency from test configuration. You can create an actual object which is dependent on the Mock and stub for testing. This also allows you to test a class even if its dependency is not yet coded.
3) Avoid static methods, they are difficult to test as they cannot be called polymorhpically.


11. What does @RunWith annotation do?
The @RunWith annotation allows you to run your JUnit test with another, custom JUnit Runner. For example, you can do some parameterized testing in JUnit by using @RunWith(Parameterized. class), this Runner is required for implementing parameterized tests in JUnit. 

Some of the popular third-party implementations of JUnit runners include SpringJUnit4ClassRunner and MockitoJUnitRunner, which you can use with @RunWith annotation to test Spring beans and Mockito library.


12. how do you test a method which doesn't return a value?
Well, you can test a method even if it doesn't return a value by checking for its side effects, for example, add() method of ArrayList doesn't return anything but it has a side effect of the increasing size of Collection by 1, so you can check whether add() is successful or not by checking the size() of List before and after calling this method as shown below:

@Test
public void testListAdd() {
 List<String> mylist = new ArrayList<>();
 assertEquals(0, mylist.size());
 collection.add("Java");
 assertEquals(1, mylist.size());
 collection.add("JUnit");
 assertEquals(2, mylist.size());
}

If a method doesn't return any value and doesn't have any side effect which means it's not doing anything and doesn't require testing.


10. What is the difference between Stub and Mock in Unit testing?
Though both Stub and Mock are tools for unit testing and used in place of actual class to facilitate unit testing there is some subtle difference between them. Mocks are generally more powerful becuase they can record method calls and there are also good frameworks like Mockito and PowerMock available, which can create Mock for you. 

Stubs are easier to use but require more coding than Mocks becuase you need to create your own Stub implementation. Many Java developers prefer mocks over stubs becuase of this reason only. I highly recommend Java developers learn Mockito along with JUnit for writing unit tests in Java. If you need a resource you can checkout Mockito: Next-Level Java Unit Testing by Adrian Weich on Udemy.  It's a great course for both beginners and experienced Java developers. 

best course to learn Mockito for Java Programmers




14. What happens when your JUnit test method throws an exception?
When a JUnit method throws an uncaught exception, which is also not declared as expected using the @Test(expected) parameter then the JUnit test will fail, but if it's declared and expected then the JUnit test will pass. If the method under test throws an exception that is caught by you inside the JUnit test method then nothing will happen and the test will be passed


15. How do you test protected Java methods using JUnit?
Since protected methods are accessible to everyone inside the same package they are declared, you can put your JUnit test class also on the same package to test them. But, don't mix your test code with real code, instead, put them on a different source tree. You can use a Maven-like structure to organize your test and source classes in different folders.


16. Can you test a private method using JUnit?
Well, since private methods are not accessible outside the class they are declared, it's not possible to test them using JUnit directly, but you can use Reflection to make them accessible by calling setAccessible(true) before testing. Another way to test private method is via public methods, which uses them. In general, testing the private method is also an indication that those methods should be moved into another class to promote reusability.

17. What are some Unit testing libraries you know other than JUnit for Java programs?
Java is very lucky to have many great unit testing libraries including JUnit. Here are a couple of the most popular ones:
  • Mockito which is a Mocking framework can be used with JUnit
  • PowerMock, similar to Mockito but also provide mocking of static methods.
  • TestNG similar to JUnit
  • Spock groovy-based unit testing framework for the Java application. Thanks to JUnit Runner, you can use the Spock testing framework with Java IDEs as well.
At a bare minimum, you should JUnit and Mockito for writing unit tests in Java. 


18. Does JUnit support Parameterized tests, where tests can be executed multiple times with different parameter values?
Yes, JUnit supports parameterized tests by using a custom Runner called Parameterized and @Parameters annotation. You use this annotation to annotate the method which provides parametric values and run the Test class with @RunWith(Parameterized. class) runner. 

You can also use object arrays to inject values. If you want some examples, I recommend checking out Practical Java Unit Testing with JUnit 5, a crash course for Java developers to learn essential JUnit features in 1-hour. 

common JUnit Interview questions with answers



19. What does @Rule annotation do?
It allows you to create JUnit rules, which can be used to add or redefine the behavior of each test method in a test class. You can write your own rules using @Rule annotation.


20. What are text fixtures in unit testing?
A test fixture in unit testing is used to provide a well-known and fixed environment in which the test can be run. A text fixture could be set up or mock objects or loading specific data from the database for testing. JUnit provides @Before and @BeforeClass annotation for creating text fixtures and @After and @Afterclass for doing cleanup.

21. What is the difference between JUnit 4 and JUnit 5?
The JUnit 5 is the latest version of JUnit also known as Jupiter.  The minimum JDK for JUnit 4 was JDK 5, while JUnit 5 requires at least JDK 8. Also, the @Before, @BeforeClass, @After, and @AfterClass annotations are now more readable than the @BeforeEach, @BeforeAll, @AfterEach, and @AfterAll annotations.

That's all in this list of 20 JUnit Interview Questions. Since unit testing is a sign of professional programmers, you must spend some time learning tricks of JUnit and the more important art of unit testing. Testable writing code is the first step towards clean code.


Other JUnit and Interview Questions resources you like it
  • Difference between Stub and Mock in Unit testing? (answer)
  • Simple JUnit example to test linked list in Java (example)
  • How to test Exception in JUnit 4? (answer)
  • JUnit 4 tip - Constructor is called before test method (tip)
  • How Assertion works in Java? (answer)
  • 20+ Spring Boot Interview Questions for Java developers (questions)
  • 15 Spring Data JPA Interview Questions (list)
  • 25 Spring Boot Interview Questions with Answers (questions)
  • 5 Best Courses to learn Java Programming  (best courses)
  • 20+ Spring Boot Testing Interview Questions (answers)
  • 130+ Java Interview Questions with Answers (list)
  • 17 Spring AOP Interview Questions with Answers (list)
  • 5 Free Courses to learn JUnit for Java developers (free courses)
Thanks a lot for reading this article so far. If you like these JUnit Interview questions and answers, then please share them with your friends and colleagues. If you have any questions or feedback or you want another course to add to this list, feel free to drop a note. All the best with your Unit testing journey.

P. S. - If you are new to Java unit testing space and looking for some free JUnit courses to start with, then you can also take a look at the JUnit 5 Quick Start: Java Unit Testing [FREE] course on Udemy. This course is completely free and more than 4500+students have already joined this course. 

No comments :

Post a Comment