JUnit Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What is JUnit?
JUnit is a software testing framework for unit testing, open Source Software maintained by the JUnit.org community. JUnit was originally written by Erich Gamma and Kent Beck.
► Test runners for running tests
► Test fixtures for sharing common test data
► Assertions for testing expected results
Ques 2. Who Should Use JUnit?
JUnit is mostly used by developers for testing their written code. JUnit is designed for unit testing, which is really a coding process, not a testing process. But many testers or QA engineers, are also required to use JUnit for unit testing.
Ques 3. Why Do You Use JUnit to Test Your Code?
► Using JUnit makes unit testing easier and faster.
► Writing more tests will make more productive, not less productive.
► Unit Tests should be done as soon as possible at the code unit level so at that point we capture the issue and fix it.
Ques 4. How To Compile a JUnit Test Class?
As JUnit code is written in java, compiling a JUnit test class is like compiling any other Java classes. The only thing you need watch out is that the JUnit JAR file must be included in the classpath like junit.jar etc. For example, to compile the test class LoginTest.java described previously, you should do this:
javac -cp junit-4.4.jar LoginTest.java
and it will create .class file.
LoginTest.class
The compilation is ok, if you see the LoginTest.class file.
Ques 5. How To Write a Simple JUnit Test Class?
You should be able to write this simple test class with one test method:
import org.junit.*;
public class LoginTest
{
@Test public void testLogin()
{
String username = \"withoutbook\";
Assert.assertEquals(\"withoutbook\", username);
}
}
Here first argument in assertEquals is the known parameter which should be equal to username. If both are same it will send me true and if both are not equal sends me false.
Ques 6. How To Run a JUnit Test Class?
A JUnit test class usually contains a number of test methods. You can run all test methods in a JUnit test class with the JUnitCore runner class. For example, to run the test class LoginTest.java described previously, you should do this:
java -cp .;
junit-4.4.jar org.junit.runner.JUnitCore LoginTest
JUnit version 4.4
Time: 0.015
OK (1 test)
This output says that 1 tests performed and passed. The same you can perform by executing build.xml also.
Ques 7. What CLASSPATH Settings Are Needed to Run JUnit?
You run your JUnit tests from a command line, from an IDE, or from "ant", you must define your CLASSPATH settings correctly. Here is what recommended by the JUnit FAQ with some minor changes:
To run your JUnit tests, you'll need the following elemements in your CLASSPATH:
* The JUnit JAR file should be there.
* Location of your JUnit test classes.
* Location of classes to be tested.
* JAR files of class libraries that are required by classes to be tested.
If found NoClassDefFoundError in your test results, then something is missing from your CLASSPATH.
If you are running your JUnit tests from a command line on a Windows system:
set CLASSPATH=c:\A\junit-4.4.jar;c:\B\test_classes;
c:\B\target_classes;
If you are running your JUnit tests from a command line on a Unix (bash) system:
export CLASSPATH=/A/junit-4.4.jar:/B/test_classes:
/C/target_classes:
Ques 8. How Do I Run JUnit Tests from Command Window?
You need to check the following list to run JUnit tests from a command window:
1. 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.
2. Make sure that the CLASSPATH is defined as shown in the previous question.
3. Invoke the JUnit runner by entering the following command:
java org.junit.runner.JUnitCore
Ques 9. How To Write a JUnit Test Method?
* You need to mark the method as a JUnit test method with the JUnit annotation: @org.junit.Test.
* A JUnit test method must be a "public" method. This allows the runner class to access this method.
* A JUnit test method must be a "void" method. The runner class does not check any return values.
* A JUnit test should perform one JUnit assertion - calling an org.junit.Assert.assertXXX() method.
Here is a simple JUnit test method:
import org.junit.*;
@Test public void testLogin() {
String username = "withoutbook";
Assert.assertEquals("withoutbook", username);
}
Ques 10. How to create a Test Suite using JUnit in Eclipse?
There are four ways to create a JUnit test suite class in Eclipse with JUnit plugin: org.junit_3.8.1. First, select the directory (usually unit-tests) that you wish to create the test suite class in.
1. Select File > New > Other... > Java > JUnit > JUnit Test Suite.
2. Select the arrow of the button in the upper left of the toolbar. Select Other... > Java > JUnit > JUnit Test Suite,
3. Right click on a package in the Package Explorer view in the Java Perspective, and select Other... > Java > JUnit > JUnit Test Suite,
4. You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestSuite as the super class of the test class you are creating.
Ques 11. How To Create Test Class in Eclipse?
1. Select File ; New ; JUnit Test Case.
2. Select the arrow of the button in the upper left of the toolbar. Select JUnit Test Case.
3. Right click on a package in the Package Explorer view in the Java Perspective, and select JUnitTestCase.
4. Click on the arrow of the icon in the toolbar. Select JUnit Test Case.
5. You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestCase as the super class of the test class you are creating.
Intermediate / 1 to 5 years experienced level questions & answers
Ques 12. Why Not Just Use a Debugger for Unit Testing?
* Automated unit testing requires extra time to setup initially. But it will save your time, if your code requires changes many times in the future.
* A debugger is designed for manual debugging and manual unit testing, not for automated unit testing. JUnit is designed for automated unit testing.
Ques 13. Why Not Just Write a main() Method for Unit Testing?
You can write a main() method in each class that needs to be tested for unit testing. In the main() method, you could create test object of the class itself, and write some tests to test its methods. However, this is not a recommended approach because of the following points:
* Your classes will be cluttered with test code in main method. All those test codes will be packaged into the final product.
* If you have a lots of classes to test, you need to run the main() method of every class. This requires some extra coding effort.
* If you want the test results to be displayed in a GUI, you will have to write code for that GUI.
* If you want to log the results of tests in HTML format or text format, you will have to write additional code.
* If one method call fails, next method calls won't be executed. You will have to work-around this.
Ques 14. Why Not Just Use System.out.println() for Unit Testing?
If we add debug statements into code, it is a low-tech method for debugging it. It usually requires that output be scanned manually every time the program is run to ensure that the code is doing what's expected.
It generally takes less time in the long run to codify expectations in the form of an automated JUnit test that retains its value over time. If it's difficult to write a test to assert expectations, the tests may be telling you that shorter and more cohesive methods would improve your design.
Ques 15. Under What Conditions Should You Test set() and get() Methods?
We should test to target areas that might break. set() and get() methods on simple data types are unlikely to break. So no need to test them.
set() and get() methods on complex data types are likely to break. So you should test them.
Ques 16. Can You Explain the Life Cycle of a JUnit3.8 Test Case Class?
Test case class contains a setUp() method, a tearDown() method and multiple testXXX() methods. When calling a test runner to run this test class, the runner will execute those methods in a specific order giving the test case class an execution life cycle like this:
setUp()
testXXX1()
tearDown()
setUp()
testXXX2()
tearDown()
Ques 17. How Often Should You Run Your JUnit Tests?
You should run all your unit tests as often as possible, ideally every time the code is changed. Make sure all your unit tests always run at 100%. Frequent testing gives you confidence that your changes didn't break anything and generally lowers the stress of programming in the dark.
For larger systems, you may just run specific test suites that are relevant to the code you're working on. Run all your acceptance, integration, stress, and unit tests at least once per day.
Experienced / Expert level questions & answers
Ques 18. Do You Need to Write a Test Class for Every Class That Need to Be Tested?
This is an interesting question.
The technical answer is no. There is no need to write one test class for each every class that need to be tested. One test class can contain many tests for many test target classes.
But the practical answer is yes. You should design one test class per test target class for low level basic tests. This makes your test classes much easier to manage and maintain. You should write separate test classes for high level tests that requires multiple target classes working together.
Ques 19. Please Explain the Life Cycle of a JUnit 4.4 Test Class?
A JUnit 4.4 test class contains a @Before method, an @After method and multiple @test methods. When calling a test runner to run this test class, the runner will execute those methods in a specific order giving the test class an execution life cycle like this:
@Before
@Test XXX1
@After
@Before
@Test XXX2
@After
Ques 20. How Do You Test a private Method?
When a method is declared as "private", it can only be accessed within the same class. So there is no way to test a "private" method of a target class from any test class.
To resolve this problem, you have to perform unit testing manually. Or you have to change your method from "private" to "protected".
Or if it is not possible to convert any of the above ways, you can test private method by using PowerMock partialMock.
Ques 21. How Do You Test a protected Method?
As a method is declared as "protected", it can only be accessed within the same package where the class is defined. To test a "protected" method of a target class, you need to define your test class in the same package as the target class.
Ques 22. Do You Have To Write a Test for Everything?
No, just test everything that could reasonably break. Keep in mind NullPointerException which occurs maximum.
Be practical and maximize your testing investment. Remember that investments in testing are equal investments in design. If defects aren't being reported and your design responds well to change, then you're probably testing enough. If you're spending a lot of time fixing defects and your design is difficult to grow, you should write more tests.
If something is difficult to test, it's usually an opportunity for a design improvement. Look to improve the design so that it's easier to test, and by doing so a better design will usually emerge.
Ques 23. How Do You Test a Method That Does not Return Anything?
You need to follow the below logics:
* If a method is not returning anything through the "return" statement (void method), it may return data through its arguments. In this case, you can test the data returned in any argument.
* Else if a method is not returning any data through its arguments, it may change values of its instance variables. In this case, you can test changes of any instance variables.
* Else if a method is not changing any instance variable, it may change values of its class variables. In this case, you can test changes of any class variables.
* Else if a method is not changing any class variable, it may change external resources. In this case, you can test changes of any external resources.
* Else if a method is not changing any external resources, it may just doing nothing but holding the thread in a waiting status. In this case, you can test this waiting condition.
* Else if a method is not holding the thread in waiting status, then this method is really doing nothing. In this case, there is no need to test this method!
Ques 24. When Should Unit Tests Should Be Written In Development Cycle?
You should write unit test before writing the code if you are a TDD (Test-Driven Development) believer. Test-first programming is practiced by only writing new code when an automated test is failing.
Good tests tell you how to best design the system for its intended use. They effectively communicate in an executable format how to use the software. They also prevent tendencies to over-build the system based on speculation. When all the tests pass, you know you're done!
Whenever a customer test fails or a bug is reported, first write the necessary unit test(s) to expose the bug(s), then fix them. This makes it almost impossible for that particular bug to resurface later. Test-driven development is gaining momentum these days compared to writing tests after the code.
Most helpful rated by users:
- Who Should Use JUnit?
- What is JUnit?
- How To Compile a JUnit Test Class?
- Why Do You Use JUnit to Test Your Code?
- How To Write a Simple JUnit Test Class?