Google News
logo
JUnit Interview Questions
JUnit is an open-source, Java-based unit testing framework that plays a crucial role in achieving the culture of TDD (Test Driven Development). The TDD culture lays strong emphasis on setting up the test data for testing a logic that would be implemented once the testing is successful.

JUnit helps to increase the software stability as it helps in identifying the bug in the code logic at an early stage without requiring the software to go to production. This helps in reducing the time required to debug any issues later on.

JUnit is the testing framework, it is used for unit testing of Java code.  

JUnit = Java + Unit Testing
Unit testing is the testing of single entity (class or method). Unit testing is very essential to every software company to give a quality product to their customers.
Executing the test cases manually without any tool support is known as manual testing.
Taking tool support and executing the test cases by using automation tool is known as automation testing.
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 tool so less tester are required in automation testing.
 
More reliable : Automation tests perform precisely same operation each time they are run.
 
Programmable : Testers can program sophisticated tests to bring out hidden information.
Following are the disadvantages of manual testing :
 
Time consuming and tedious : Since test cases are executed by human resources so it is very slow and tedious.
 
Huge investment in human resources : As test cases need to be executed manually so more testers are required in manual testing.
 
Less reliable : Manual testing is less reliable as tests may not be performed with precision each time because of human errors.
 
Non-programmable : No programming can be done to write sophisticated tests which fetch hidden information.
Following are the features of JUnit :
 
* JUnit is an open-source framework.
* Supports automated testing of test suites.
* Provides annotations for identifying the test methods.
* Provides assertions to test expected results or exceptions of the methods under test.
* Provides a platform for running test cases automatically and checking their results and giving feedback.
Some of the annotations provided by JUnit are as follows :
 
* @Test : This annotation over a public method of void return type can be run as a test case. This is a replacement of the org.junit.TestCase annotation.

* @Before : This is used when we want to execute the preconditions or any initialisation based statements before running every test case.

* @BeforeClass : This is used when we want to execute statements before all test cases. The statements may include test connections, common setup initialisation etc.

* @After : This is used when we want to execute statements after each test case. The statements can be resetting the variables, deleting extra memory used etc.

* @AfterClass : This is used when certain statements are required to be executed after all the test cases of the class are run. Releasing resource connections post-execution of test cases is one such example.

* @Ignores : This is used when some statements are required to be ignored during the execution of test cases.

* @Test(timeout=x) : This is used when some timeout during the execution of test cases is to be set. The value of x is an integer that represents the time within which the tests have to be completed.

* @Test(expected=NullPointerException.class) : This is used when some exception thrown by the target method needs to be asserted.

Fixture represents a fixed state of object sets used as a baseline for running test methods. This is to ensure there is a fixed and well-known environment where the results of the test methods are repeatable when run multiple times. The fixture has the following 2 methods :
 
* setUp() This runs before every test case is run.
* tearDown() This method is run after every test is run.

Mocking is a phenomenon where an object mimics a real object. Whereas, stubbing are the codes responsible for taking place of another component. Mockito, EasyMock are some of the mocking frameworks in Java.
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.
Here are some of the best practices you can follow to make your code more testable :
 
* Use interface instead of concrete class, this allows the tester to replace actual class with Mock or Stub for testing purposes.
 
* 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.
 
* Avoid static methods, they are difficult to test as they cannot be called polymorhpically.
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.
JUnit is also known as a waning testing framework. JUnit is extensively used by developers to carry out unit testing in Java. Moreover, it is also being used to speed up the application based on Java. It is important to note that by taking into account the source code, the application can efficiently be sped up.
The JUnit test framework is associated with the providence of these critical features. They are as follows :
 
* Test Suites
* JUnit Classes
* Fixtures
* Test Runners
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.
A test fixture is also known as a regulated state of objects that can be used as a platform for running the tests. The primary purpose is to make sure that there is a known climate in which the development tests can be run. Various examples can be cited in this context. They are as follows :
 
* Copying the fixed known set of files
* Preparing the input data and the creation of mock and fake objects
* Assessing a database with fixed and known sets of data

It is also essential for you to note that if a group of tests shares the same fittings, one needs to write a different setup code. On the other hand, if the group of assessments is in need of a different test fixture, one can write the code alongside the test procedure. In this manner, one can create the best accessory related to a test.
@RunWith annotation lets us run the JUnit tests with other custom JUnit Runners like SpringJUnit4ClassRunner, MockitoJUnitRunner etc. We can also do parameterized testing in JUnit by making use of @RunWith(Parameterized.class).
These are the annotations present in JUnit 4. Methods annotated with @Before will be called and run before the execution of each test case. Methods annotated with @After will be called and executed after the execution of each test case. If we have 5 test cases in a JUnit class, then the methods annotated with these two would be run 5 times. In JUnit 5, the annotations @Before and @After are renamed to @BeforeEach and @AfterEach for making it more readable.
If we use System.out.println() for debugging, then we would have to do a manual scan of the outputs every time program is executed to ensure that the output printed is the expected output. Also, in the longer run, writing JUnit tests will be easier and will take lesser time. Writing test cases will be like an initial investment and then, later on, we can later automatically test them on the classes.
The extent to which the source code is unit tested is called coverage. There are three types of coverage techniques, they are :
 
* Statement coverage : This ensures that each statement/line in the source code is executed and tested.
* Decision coverage : This ensures that every decision point that results in true or false is executed and run.
* Path coverage : This ensures that every possible route from a given point is run and tested.
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
In order to install JUnit, you need to follow the below-mentioned procedures.

They are as follows :
 
* You have to download the latest version of JUnit which is available over the internet by the file name of JUnit.zip.

* In the next process, you have to unzip the JUnit.zip file to a separate directory also referred to as the %JUNIT_HOME%
 
* Next, make sure that you add JUnit to the classpath set  CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar

* You can also test the installation by the use of sample tests. However, you have to run them. Interestingly, the sample tests are located in the installation directly. Then you have to type java org.junit.runner.JUnitCore org.junit.tests.AllTests to run various kind of tests
 
* It is important to note that all the tests should pass with an OK message. In case the tests do not pass, you have to make sure that the file is located in the CLASSPATH
As code cyclomatic complexity is determined based on number of decision points within the code and hence execution paths, higher cyclomatic complexity makes it difficult to attain achieve test/code coverage.
@Before annotation :
 
syntax :
@Before
public void myMethod()
 
This method should execute before each test. Such methods are generally used for initialization before performing a actual test in 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 test.
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

There are different ways of exception handling in JUnit.
* Try catch idiom.
* Using JUnit rule.
* @Test annotation.
* Using catch exception library.
* Using customs annotation.
XPath also called XML Path is a language to query XML documents. It is an important strategy to locate elements in selenium. It consists of a path expression along with some conditions. Here, you can easily write XPath script/query to locate any element in the webpage. It is designed to allow the navigation of XML documents, with the purpose of selecting individual elements, attributes, or some other part of an XML document for specific processing. It also produces reliable locators.
Absolute XPath : It is the direct way to find the element, but the disadvantage of the absolute XPath is that, if there are any changes made in the path of the element then that XPath gets failed. For example : /html/body/div[1]/section/div[1]/div
 
Relative XPath : For Relative XPath, the path starts from the middle of the HTML DOM structure. It begins with the double forward slash (//), which means it can search the element anywhere at the webpage. For example : //input[@id=‘ap_email’]

To access a website, a user sends a “request” to that website’s server, and the server sends back a response in the form of the website you want to access. To load test a website, quality assurance engineers and automation engineers just need to multiply the number of responses sent to simulate different traffic loads. The web server’s response to the influx of virtual users can then be measured. This is used to determine performance issues and server capacity.
Mockito is an open-source, Java-based, mocking framework that allows the creation of test objects that simulate the behaviour (mock) of real-world objects. This helps in achieving test-driven or behaviour-driven development. The framework allows developers to verify system behaviours without establishing expectations. Mockito framework attempts to eliminate expect-run-verify development patterns by removing external specifications and dependencies. Some of the advantages of Mockito are :
 
* Mocks are created at runtime, hence reordering method input parameters or renaming interface methods will not break test code.
* Mockito supports returning of values.
* It supports exception simulation
* It provides a check on the order of method calls.
* It helps in creating mock objects using annotation.
thenReturn and doReturn are used for setting up stubs and are provided by the Mockito framework. They are generally used along with when clause as --> when-thenReturn and doReturn-when. when-thenReturn is used in most cases due to better readability. 
 
Following are the differences between thenReturn and doReturn :
 
* Type safety : doReturn takes Object parameter, unlike thenReturn. Hence there is no type check in doReturn at compile time. In the case of thenReturn, whenever the type mismatches during runtime, the WrongTypeOfReturnValue exception is raised. This is why when-thenReturn is a better option whenever we know the type.

* No side-effect : Since doReturn does not have type safety, there are no side effects when it is being used. Whenever thenReturn is used, if the type mismatch occurs, an exception is thrown which might result in the abortion of test cases.
@Mock annotation is used for creating mocks whereas @InjectMocks is used for creating class objects. Whenever the actual method body has to be executed of a given class, then we can use @InjectMocks.
Static methods belong to the class and not to any objects which means that all instances of the class use the same static method. They are more like procedural code and are used in legacy systems. Mock libraries create mocks at runtime utilizing dynamic instance creation using interfaces or inheritance. Since static methods are not linked with any instance, it is not possible to mock them using Mockito. However, we have frameworks like PowerMock that supports static methods.
Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters). The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it. Cactus implements an in-container strategy, meaning that tests are executed inside the container.
Cactus Ecosystem is made of several components :
 
  * Cactus Framework is the heart of Cactus. It is the engine that provides the API to write Cactus tests.
 
  * Cactus Integration Modules are front ends and frameworks that provide easy ways of using the Cactus Framework (Ant scripts, Eclipse plugin, Maven plugin).
WebUnit is a Java-based testing framework for web applications. It wraps existing testing frameworks such as HtmlUnit and Selenium with a unified, simple testing interface to allow you to quickly test the correctness of your web applications.
JWebUnit provides a high-level Java API for navigating a web application combined with a set of assertions to verify the application's correctness. This includes navigation via links, form entry and submission, validation of table contents, and other typical business web application features.
 
The simple navigation methods and ready-to-use assertions allow for more rapid test creation than using only JUnit or HtmlUnit. And if you want to switch from HtmlUnit to other plugins such as Selenium (available soon), there is no need to rewrite your tests.