JUnit Interview Questions and Answers

JUnit Interview Questions and Answers

Last updated on 27th Sep 2020, Blog, Interview Question

About author

Damodharan (Junit Project Manager )

Highly Expertise in Respective Industry Domain with 10+ Years of Experience Also, He is a Technical Blog Writer for Past 4 Years to Renders A Kind Of Informative Knowledge for JOB Seeker

(5.0) | 12365 Ratings 948

JUnit Interview Questions and Answers will guide us now that JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks collectively known as xUnit that originated with SUnit. So learn JUnit by this JUnit Interview Questions with Answers guide

1. What is Testing?

Ans:

Testing is the process of checking the functionality of the application whether it is working as per requirements.

2. What is Unit Testing?

Ans:

Unit testing is the testing of a single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.

3. What is JUnit?

Ans:

  • JUnit is a Regression Testing Framework used by developers to implement unit testing in Java and accelerate programming speed and increase the quality of code.
  • JUnit is the testing framework, it is used for unit testing of Java code.
  • JUnit = Java + Unit Testing

4. What is Manual testing?

Ans:

Executing the test cases manually without any tool support is known as manual testing.

5. What is Automated testing?

Ans:

Taking tool support and executing the test cases by using automation tools is known as automation testing.

6. What is the difference between manual testing and automated testing?

Ans:

Manual testing is performed by humans, so it is time-consuming and costly. Automated testing is performed by testing tools or programs, so it is fast and less costly.

Give some disadvantages of manual testing.

Following are some disadvantages of manual testing:

  1. 1. The testing is very time consuming and is very tiring.
  2. 2. The testing demands a very big investment in the human resources.
  3. 3. The testing is less reliable
  4. 4. The testing cannot be programmed.

7. How is the testing of the ‘private’ method done?

Ans:

There is no direct way for testing of the private method; hence manual testing is to be performed, or the method is changed to a “protected” method.

8. How to install JUnit?

Ans:

Installation steps for JUnit :

  1. 1. Download the latest version of JUnit, referred to below as junit.zip.
  2. 2. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
  3. 3. Add JUnit to the classpath − set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
  4. 4. Test the installation by running the sample tests distributed with JUnit (sample tests are located in the installation directory directly, not the junit.jar file).
  5. 5. Then simply type − java org.junit.runner.JUnitCore org.junit.tests.AllTests
  6. 6. All the tests should pass with an “OK” message. If the tests don’t pass, verify that junit.jar is in the CLASSPATH.

9. What is a Unit Test Case?

Ans:

A Unit Test Case is a part of code which ensures that the other part of code (method) works as expected. A formal written unit test case is characterized by a known input and by an expected output, which is worked out before the test is executed. The known input should test a precondition and the expected output should test a post condition.

10. Why does JUnit only report the first failure in a single test?

Ans:

Reporting multiple failures in a single test is generally a sign that the test does too much and it is too big a unit test. JUnit is designed to work best with a number of small tests. It executes each test within a separate instance of the test class. It reports failure on each test.

Subscribe For Free Demo

Error: Contact form not found.

11. In Java, assert is a keyword. Won’t this conflict with JUnit’sassert() method?

Ans:

JUnit 3.7 deprecated assert() and replaced it with assertTrue(), which works exactly the same way. JUnit 4 is compatible with the assert keyword. If you run with the -ea JVM switch, assertions that fail will be reported by JUnit.

12. When are the unit tests pertaining to JUnit written in Developmental Cycle?

Ans:

The unit tests are written before the development of the application. It is so because by writing the check before coding, it assists the coders to write error-free codes which further boosts the viability of the form.

13. Shed light on the variety of JUnit classes and make a proper list of them

Ans:

The JUnit classes are essential classes that are usually utilized in testing and writing the JUnits. 

Here is the list of the critical JUnit test classes.

  1. 1. Test Suite: It is also known as a composition of various tests
  2. 2. Assert: It is a set of assertive procedures used to design an application
  3. 3. Test Result: It is associated with the collection of results while executing a test case
  4. 4. Test Case: It is that kind of a JUnit class which is related to various fixtures. It also has the ability to run on a variety of tests

14. What is Junit Test Fixture?

Ans:

A test fixture is a fixed state of a set of objects used as a baseline for running tests. Their purpose is to ensure that there is a well known and fixed environment in which tests are run so that results are repeatable. 

15. What are the critical fixtures of JUnit?

Ans:

The JUnit test framework is associated with the providence of these critical features. They are as follows:

  • Test Suites
  • JUnit Classes
  • Fixtures
  • Test Runners

16. What do you understand by a fixture?

Ans:

The fixture is a set of objects of a fixed state that is used as a baseline for running tests. The objective of a test fixture is to make sure that there is a well known and fixed environment to run tests so that results can be repeated. 

It includes the following two methods −

  1. 1. setUp() method – it runs before every test is called.
  2. 2. tearDown() method – it runs after every test method is called.

17. Name some Junit extensions?

Ans:

Following are some of the JUnit extensions −

  • Cactus
  • JWebUnit
  • XMLUnit
  • MockObject

18. What do you understand by JWebUnit? And what are its advantages?

Ans:

This is the most popular Junit Interview Questions asked in an interview. WebUnit is also a Java-based testing framework to test web applications. It wraps around existing testing frameworks to allow quick testing of web applications and comes with a unified, simple testing interface.

To verify the correctness of an application, JWebUnit provides a high-level Java API to test a web application along with a set of assertions. This includes navigation through links and forms entry and submission. It also involves validation of table contents and other usual business web application features.The easy navigation methods that come with ready-to-use assertions allow for more rapid test creation than using Junit or HtmlUnit only. And if switching from HtmlUnit to other plugins such as Selenium are needed there should be no need to rewrite tests.

19. What is @Test and where it’s used?

Ans:

@Test annotation is used to mark a method as a test method, the result of which is then compared with expected output to check whether the test is successful or not.

20. What is @Before and @BeforeClass and it’s usage?

Ans:

@Before annotation syntax:

  • @Before
  • public void myMethod()

This method should execute before each test. Such methods are generally used for initialization before performing an actual test in a test environment.

@BeforeClass annotation syntax:

  • @BeforeClass
  • public static void myMethod()

This method should execute before all the tests. It executes only once. Method should be declared static. Mostly used for database connectivity tasks before execution of any of the tests.

21. How will you run JUnit from the command window?

Ans:

To run JUnit tests from a command window, you need to check the following list:

Make sure that JDK is installed and the “java” command program is accessible through the PATH setting. Type “java -version” at the command prompt, you should see the JVM reports you back the version string.

Make sure that the CLASSPATH is defined as shown in the previous question. Invoke the JUnit runner by entering the following command:

  • java org.junit.runner.JUnitCore

22. How @Test annotation is used for testing exceptions?

Ans:

  • @Test (expected = Exception.class)

Limitation: It is used for testing only a single exception.

23. How to write a simple Junit test class?

Ans:

  • To write a test case, follow these steps:
  • Define a subclass of TestCase.
  • Override the setUp() method to initialize object(s) under test.
  • Optionally override the tearDown() method to release object(s) under test.
  • Define one or more public testXYZ() methods that exercise the object(s) under test and assert expected results.

24. What are the top advantages of writing unit tests?

Ans:

The advantages of writing unit tests include Design testability, Code testability and Code maintainability as good unit tests enforce Object Oriented principles such as Single Responsibility etc. which enables people to avoid code smells such as long classes, long methods, large conditionals etc.

25. How is code cyclomatic complexity related to unit tests?

Ans:

As code cyclomatic complexity is determined based on the number of decision points within the code and hence execution paths, higher cyclomatic complexity makes it difficult to attain test/code coverage.

Course Curriculum

Best JUnit Training with Industry Standard Modules By Top-Rated Instructors

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

26. What is mocking and stubbing? Did you use any mocking framework?

Ans:

Mocking is a feature where an object mimics like a real object. Stubbing are codes that are responsible for taking the place of another component.

There are various different Java mocking frameworks such as Mockito, EasyMock etc.

27. In SDLC, When is the right time to start writing unit tests?

Ans:

Test-along if not test-driven; Writing unit tests towards end is not very effective. Test-along technique recommends developers to write the unit tests as they go with their development.

28. Write a sample unit testing method for testing an exception named as IndexOutOfBoundsException when working with ArrayList?

Ans:

  • @Test(expected=IndexOutOfBoundsException.class)
  • public void outOfBounds() {
  • new ArrayList().get(1);
  • }

29. Write a sample unit testing method for testing timeout? @Test(timeout=100)

Ans:

  • public void infinity() {
  • while(true);
  • }

30. Name some code smells which makes it hard to achieve high code coverage?

Ans:

  1. 1. Long method
  2. 2. Large conditionals

31. What are the different methods of exception handling in JUnit?

Ans:

There are different ways of exception handling in JUnit. Try to catch idioms.

Using JUnit rule.

@Test annotation.

  1. 1. Using the catch exception library.
  2. 2. Using customs annotation.

32. How do I execute JUnit from the command line?

Ans:

Executing Junit from the command line involves 2 steps. 

  1. 1.set the ClassPath to include JUnit core libraries. set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
  2. 2.Invoke JunitCore. java org.junit.runner.JUnitCore

33. How do I test a private method?

Ans:

The private methods cannot be tested as any private method only be accessed within the same class. The private method needs to be tested manually or be converted to a protected method.

34. What happens if a test method throws an exception?

Ans:

The JUnit runner will declare that test as fail when the test method throws an exception.

35. The methods Get () and Set () should be tested for which conditions?

Ans:

Unit tests performed on java code should be designed to target areas that might break. Since the set() and get() methods on simple data types are unlikely to break, there is no need to test them explicitly. On the other hand, set() and get() methods on complex data types are vulnerable to break. So they should be tested.

36. What is JUnit parameterized test?

Ans:

The parameterized test is a new feature introduced in JUnit 4. It provides the facility to execute the same test case again and again with different values.

37. Name the tools with which JUnit can be easily integrated.

Ans:

JUnit Framework can be easily integrated with either of the followings − 

  • Eclipse
  • Ant
  • Maven

38. Difference between Assert and Verify ?

Ans:

Assert works only if assertions ( -ea ) are enabled which is not required for Verify. Assert throws an exception and hence doesn’t continue with the test if assert evaluates to false whereas it’s not so with Verify.

39. Place the JUnit program in the context of the current evolution of tech and programming.

Ans:

Junit is known as a waning testing framework. It is extensively utilized by developers to carry out unit testing in Java. At the same time, it is also commonly used to speed up applications based in Java. It is crucial to note that, through a consideration of the source code, the application would be efficiently sped up.

40. How to Run Your JUnit 4.4 Tests with a JUnit 3.8 Runner?

Ans:

junit.framework.JUnit4TestAdapter class included in JUnit 4.4 JAR file. Here is sample code:

  • import junit.framework.Test;
  • import junit.textui.TestRunner;
  • import junit.framework.JUnit4TestAdapter;
  • public class JUnit3Adapter {
  • public static void main (String[] args) {
  • Test adaptedTest = new JUnit4TestAdapter(HelloTest.class);
  • TestRunner.run(adapted Test);
  • }
  • }

41. Is the use of ‘main’ method possible for unit testing?

Ans:

Yes

42. Give a brief account of the Test Suite with respect JUnit

Ans:

Test Suite usually refers to the principle of compiling a variety of unit test cases to run it concurrently. In this context, it is interesting to note that in JUnit, both Run With and Suite comments are being used to avail maximum benefits.

43. What is the purpose of @AfterClass annotation in JUnit?

Ans:

This will perform the method after all tests have finished. This can be used to perform clean-up activities.

44. How does the execution procedure of the Junit test work as API methods?

Ans:

JUnit execution procedure works as described below

  • The method annotated as @BeforeClass executes only once and first of all.
  • A method annotated as @AfterClass executes only once and at the last.
  • Before executing the test, the case method annotated as @Before executes for each test case, runs.
  • The method annotated as @After executes for each test case but it runs after the execution of a test case.
  • In between those two methods annotated as @Before and method annotated as @After each test case executes.

45. How to create Parameterized tests?

Ans:

There are five steps to create Parameterized tests

  1. 1. First, the test class is annotated with @RunWith which is a Parameterized.class.
  2. 2. Then create a public static method that is annotated with @Parameters. it returns a Collection of Objects as a test data set.
  3. 3. Next, create a public constructor which takes in one row of test data.
  4. 4. Create an instance variable that is for each column of the test data row.
  5. 5. Create test case(s) using the instance variables as a source of the test data.
  6. 6. The test case invokes once per each row of data.
Course Curriculum

Enroll in JUnit Training Course and Get Hired by TOP MNCs

Weekday / Weekend BatchesSee Batch Details

46. What is XMLUnit? What is the use of supporting classes in XMLUnit?

Ans:

  • XMLUnit is used as a single JUnit extension class, XMLTestCase, and a set of supporting classes.
  • Supporting classes assertions are made about following
  • The distinction between two pieces of XML such as through Diff and DetailedDiff classes.
  • The validation of a piece of XML through the Validator class.
  • The result of transforming a piece of XML using XSLT through Transform class.
  • The evaluation of an XPath expression from an XML through classes that implement the XPath engine interface.
  • Individual nodes in a piece of XML which are exposed by DOM Traversal through Node Test class.

47. Is it necessary to write the test class to test every class?

Ans:

No

48. If the JUnit method’s return type is ‘string’, what will happen?

Ans:

JUnit test methods are designed to return ‘void’. So the execution will fail.

49. What does the test runner do?

Ans:

The test runner is used to execute the test cases.

50. Is it necessary to write the test case for every logic?

Ans:

No, we should write the test case only for that logic that can be reasonably broken.

51.What does Assert class?

Ans:

Assert class provides methods to test the test cases.

52. What does XML Unit provide?

Ans:

The Junit extension class, XMLTestCase and a set of supporting classes is provided by the XMLUnit.

53. List the core components of Cactus.

Ans:

  1. 1. Cactus Framework
  2. 2. Cactus Integration Module

54. What are the methods in fixtures?

Ans:

  • setup
  • tearDown

55. What is the use of @Test annotation?

Ans:

The @Test annotation is used to mark the method as the test method.

56. What is the test suit?

Ans:

The test suit allows us to group multiple test cases so that it can be run together. TestSuit is the container class under junit.framework.TestSuite package.

57. What are the important JUnit annotations?

Ans:

The test runner is used to execute the test cases.

  • Test
  • BeforeClass
  • Before
  • After
  • AfterClass

58.What is the purpose of @BeforeClass annotation in JUnit?

Ans:

Annotating a public static void method with @BeforeClass causes it to be run once before any of the test methods in the class.

59. Give a thorough analysis of  Joint Test API Methods

Ans:

Here is the following list of the execution procedures which would help to analyze the problem. It is as follows:

  • In the first step, you need to use the annotation in the form of @before class
  • Secondly, make sure that you use the annotation @after class
  • Subsequently, before executing the test class, make sure that you use @before performs
  • Lastly, use @before so that the application development process is smooth and is hassle free

60. What is the purpose of org.junit.Assert class?

Ans:

This class provides a set of assertion methods useful for writing tests. Only failed assertions are recorded.

61. Mention what are parameterized tests?

Ans:

Parameterized tests enable developers to perform the same test over and again using different values.

62. Explain what is ignored in JUnit?

Ans:

When your code is not ready, and it would fail if executed then you can use @Ignore annotation.

It will not execute a test method annotated with @Ignore

It will not execute any of the test methods of test class if it is annotated with @Ignore

63. Explain who should use JUnit – a developer or tester? Why do you use JUnit to test your code?

Ans:

  • JUnit is more often used by developers to implement unit tests in JAVA.  It is designed for unit testing that is more a coding process and not a testing process. However, many testers and QA engineers use JUnit for unit testing.
  • JUnit is used because
  • It test early and does automate testing
  • JUnit tests can be compiled with the build so that at unit level, regression testing can be done
  • It allows test code re-usage
  • JUnit tests behave as a document for the unit tests when there is a transfer

64. Explain what a JUnitCore Class is?

Ans:

JUnitCore class is an inbuilt class in JUnit package; it is based on Façade design pattern, this class is used to run only definite test classes only.

65. Explain how you can run JUnit from the command window?

Ans:

To run JUnit from the command window, you have to follow the steps

  1. 1. Set the CLASSPATH
  2. 2. Invoke the runner
junit Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

66. What is @After and @AfterClass and it’s usage?

Ans:

@After annotation syntax:

  • @After
  • public void myMethod()

This method should be executed after each test and used for cleaning up the test and temporary data to avoid memory issues.

@AfterClass annotation syntax:

  • @AfterClass
  • public static void myMethod()

This method should execute at the end, once all the tests are finished. Method should be declared static and executes only a single time. Mostly used for closing the database connection.

67. What is @Ignore and when it’s used?

Ans:

@Ignore is used to ignore a test method. It’s really useful when we have all the tests in advance but the code is yet to be tested for the particular test, in such scenarios such test methods should be marked with @Ignore annotation.

68. What is the purpose of @After annotation in JUnit?

Ans:

If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method.

69. What is JUnitCore class?

Ans:

This class is mainly responsible for executing tests. The org.junit.runner.JUnitCore class has a runClasses() method, which allows us to run one or more test classes. As an output we get a Result (org.junit.runner.Result) object, which we use to filter out the test information.

70. What is the Parameterized test in JUnit and what all annotations used for this?

Ans:

Parameterized tests are possible in JUnit and they provide us the liberty of passing parameters into the test classes.

  1. 1. @RunWith(Parameterized.class) – For making a class parameterized.
  2. 2. @Parameters – Parameterized class must have a static method for generating and returning a collection of arrays, this method should be marked with @Parameters annotation.

71. What’s the use of @Rule annotation?

Ans:

@Rule annotation is used for creating objects, which later can be used in test methods.

72. When you should run a JUnit test, Is there any particular time interval between each run?

Ans:

No, there is no time constraint. A JUnit test needs to run whenever there is a change in the source code. This ensures that the new change passes through all the tests.

73. Can we change the return type of JUnit test method from void to some other type?

Ans:

Ideally you should not do this. All the JUnit test methods should have a void return type. If you change the return type then the test method would not be considered as a test method and would be ignored during execution of tests.

74. Is it possible to pass command-line arguments to a test execution?

Ans:

Yes, It’s possible to pass command line arguments to a test execution –

You should use this command:

  • D JVM command-line options

75. What is the purpose of @Before annotation in JUnit?

Ans:

Several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before each Test method.

76. What are the advantages of automated testing?

Ans:

Following are the advantages of automated testing

Fast − Automation runs test cases significantly faster than human resources.

Less investment in human resources − Test cases are executed by using automation tools so less testers are required in automation testing.

More reliable − Automation tests perform precisely the same operation each time they are run.

Programmable − Testers can program sophisticated tests to bring out hidden information.

77. How is the testing of the ‘protected’ method done?

Ans:

To test the protected method, the test class is declared in the same package as the target class.

78. How do one do exception handling unit tests using @Test annotation?

Ans:

  • @Test(expected={
  •    exception class
  • }

For example:

  • @Test(expected=IllegalArgumentException.class)

79. What are called test smells in relation to unit testing?

Ans:

Following could be termed as test smells: Multiple assertions within one unit test, long-running unit tests etc

80. When are Unit Tests written in the Development Cycle?

Ans:

Tests are written before the code during development in order to help coders write the best code.

81. What is the purpose of org.junit.TestSuite class?

Ans:

A TestSuite is a Composite of Tests. It runs a collection of test cases.

82. What is the purpose of org.junit.TestResult class?

Ans:

A TestResult collects the results of executing a test case. It is an instance of the Collecting Parameter pattern. The test framework distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like an ArrayIndexOutOfBoundsException.

83. How do I test things that must be run in a J2EE container (e.g. servlets, EJBs)?

Ans:

Refactoring J2EE components to delegate functionality to other objects that don’t have to be run in a J2EE container will improve the design and testability of the software. Cactus is an open source JUnit extension that can be used for unit testing server-side java code.

Are you looking training with Right Jobs?

Contact Us

Popular Courses