Top 35+ JUnit Interview Questions & Answers [ JAVA TRICKS ] |ACTE
JUnit Interview Questions and Answers

Top 35+ JUnit Interview Questions & Answers [ JAVA TRICKS ]

Last updated on 15th Jun 2020, Blog, Interview Questions

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) | 16547 Ratings 1720

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 which is collectively known as xUnit that originated with SUnit.In the case of web applications JUnit is used to test the application without a server. This framework builds a relationship between development and testing process.

1. 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.

2. What are the different methods of testing?

Ans:

There are three methods of software testing and they are as follows:

  • Black-Box Testing
  • White-Box Testing
  • Grey-Box Testing

Black-box testing: It is a testing strategy based solely on requirements and specifications. In this strategy, it requires no knowledge of internal paths, structures, or implementation of the software being tested.

White box testing: It is a testing strategy based on internal paths, code structures, and implementation of the software being tested. White box testing generally requires detailed programming skills.

Gray box testing: It is a strategy for software debugging in which the tester has limited knowledge of the internal details of the program.

3. What are the different levels of testing?

Ans:

There are mainly four testing levels and they are:

  • Unit Testing
  • Integration Testing
  • System Testing
  • Acceptance Testing

Basically, it starts with the Unit Testing phase and ends with Acceptance Testing.

4. What do you understand by JUnit classes? List some of Junit classes.

Ans:

This is the most common Junit Interview Questions asked in an interview. JUnit classes are those classes which are used in writing and testing Junit programs. Some of the important Junit classes are mentioned below –

  • Assert – A set of assert methods.
  • TestCase − A test case that defines the fixture to run multiple tests.
  • TestResult − It contains methods that collect the results after a test case is executed.
  • TestSuite − It is an aggregate of Junit tests.

5. What is a test case?

Ans:

A test case is nothing but a set of conditions or variables under which a tester will determine whether a system under test satisfies requirements or works correctly. 

6. List out some advantages of automated testing.

Ans:

Some of the advantages of automated testing are:

  • It is very fast.
  • Investment is very less.
  • Testing is more reliable.
  • The testing can be programmed.

7. What is Verification and Validation in Software Testing?

Ans:

Verification: It is a static analysis technique. Here, testing is done without executing the code. Examples include – Reviews, Inspection, and walkthrough.

Validation: It is a dynamic analysis technique where testing is done by executing the code. Examples include functional and non-functional testing techniques.

In the V model, the development and QA activities are done simultaneously. There is no discrete phase called Testing, rather testing starts right from the requirement phase.  The verification and validation activities go hand in hand.

8. What is usability testing?

Ans:

It is a testing methodology where the end customer is asked to use the software to see if the product is easy to use, to see the customer’s perception and task time. An accurate way to finalize the customer point of view for usability is by using prototype or mock-up software during the initial stages.

9. 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.

Examples of fixtures:

  • Loading a database with a specific, known set of data
  • Copying a specific known set of files
  • Preparation of input data and setup/creation of fake or mock objects

If a group of tests shares the same fixtures, you should write a separate setup code to create the common test fixture. If a group of tests requires different test fixtures, you can write code inside the test method to create its own test fixture.

10. On what basis the acceptance plan is prepared?

Ans:

Basically, the acceptance document is prepared using the following inputs.

  • Requirement document: It specifies what exactly is needed in the project from the customers perspective.
  • Input from the customer: This can be discussions, informal talks, emails, etc.
  • Project plan: The project plan prepared by the project manager also serves as good input to finalize your acceptance test.

11. What is coverage and what are the different types of coverage techniques?

Ans:

The parameter used in software testing to describe the extent to which the source code is tested is known as coverage. There are three basic types of coverage techniques and they are:

  • Statement coverage: It ensures that each line of source code has been executed and tested.
  • Decision coverage: It assures that every decision (true/false) in the source code has been executed and tested.
  • Path coverage: Here we ensure that every possible route through a given part of the code is executed and tested.

12. What are the benefits of Automation testing?

Ans:

Benefits of Automation testing are:

  • Supports execution of repeated test cases
  • Aids in testing a large test matrix
  • Enables parallel execution
  • Encourages unattended execution
  • Improves accuracy thereby reducing human-generated errors
  • Saves time and money

13. Why is Selenium a preferred tool for Automation testing?

Ans:

Selenium is an open source tool which is used for automating the tests carried out on web browsers. Since Selenium is open-source, there is no licensing cost involved, which is a major advantage over other testing tools. Other reasons behind Selenium’s ever-growing popularity are:

  • Test scripts can be written in any of these programming languages: Java, Python, C#, PHP, Ruby, Perl &.Net
  • Tests can be carried out in any of these OS: Windows, Mac or Linux
  • Tests can be carried out using any browser: Mozilla Firefox, Internet Explorer, Google Chrome, Safari or Opera
  • It can be integrated with tools such as TestNG & JUnit for managing test cases and generating reports
  • It can be integrated with Maven, Jenkins & Docker to achieve Continuous Testing

14. What are the various components of Selenium?

Ans:

Different components of Selenium are:

  • Selenium Integrated Development Environment (IDE)
  • Selenium Remote Control (RC)

15. What are the different types of locators in Selenium?

Ans:

The locator is nothing but an address that identifies a web element uniquely within the webpage. Thus, to identify web elements accurately and precisely we have different types of locators in Selenium as follows:

  • ID
  • ClassName
  • Name
  • TagName
  • linkText
  • PartialLinkText
  • Xpath
  • CSS Selector
  • DOM

16. What is XPath?

Ans:

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.

17. What is the difference between Absolute and Relative Path?

Ans:

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’]

18. What are the different exceptions in Selenium WebDriver?

Ans:

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:

  • TimeoutException
  • NoSuchElementException
  • ElementNotVisibleException
  • StaleElementException

19. When should I use Selenium Grid?

Ans:

Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution, testing under different environments and saving execution time remarkably.

20. How do I launch the browser using WebDriver?

Ans:

The following syntax can be used to launch the Browser:

  • WebDriver driver = new FirefoxDriver();
  • WebDriver driver = new ChromeDriver();
  • WebDriver driver = new InternetExplorerDriver();

Intermediate Level Software Testing Interview Questions

    Subscribe For Free Demo

    21. Should testing be done only after the build and execution phases are complete?

    Ans:

    Testing is always done after the build and execution phases Earlier we catch a defect, the more cost effective it is. For example, fixing a defect in maintenance is ten times more costly than fixing it during execution.

    22. What are the Cactus extensions? And what are its common components?

    Ans:

    Cactus is a simple test framework. It is for unit testing server-side java code such as servlets, EJBs and Tag Libs. The idea of Cactus is to minimize the cost of writing tests on server-side code. It uses Junit internally and extends the same. The way cactus implements it is through an in-container strategy.

    • Cactus Ecosystem is made of many components
    • Cactus Framework is the core of Cactus. To write Cactus tests, it has an API.
    • Cactus Integration Modules is another component which are front ends and frameworks that provide quicker ways of using the Cactus Framework be it Ant scripts or Eclipse plugin or Maven plugin.

    23. Define installation with respect to JUnitD

    Ans:

    A fixture is also known as a constant state of a collection of objects that can be used for the execution of tests. The main aim of using a test fixture lies in the fact that there should be a familiar and fixed environment. Moreover, these tests are run so that the results are repeatable. It comprises the following procedures.

    • The setup method which runs every test
    • The teardown procedure which runs after the execution of a particular test

    24. What do you mean by regression and confirmation testing?

    Ans:

    • Regression Testing: It is defined as a type of software testing to confirm that a recent code change has not adversely affected existing features.
    • Confirmation Testing: When a test fails because of the defect, the defect is reported. Then a new version of the software is submitted whose defect is fixed. This is called confirmation testing or re-testing.

    25. What do you mean by boundary value analysis?

    Ans:

    Boundary Value Analysis (BVA) is a black box test design technique which is applied to see if there are any bugs at the boundary of the input domain.

    26. Mention different methods of exception handling in JUnit?

    Ans:

    There are different methods of exception handling in JUnit

    • Try catch idiom
    • With JUnit rule
    • With @Test annotation
    • With catch exception library
    • With customs annotation

    27. On what basis you can arrive at an estimation for your project?

    Ans:

    To estimate your project, you have to consider the following points:

    • Divide the whole project into the smallest tasks
    • Allocate each task to team members
    • Estimate the effort required to complete each task
    • Validate the estimation

    28. Which test cases are written first: white boxes or black boxes?

    Ans:

    Usually, black box test cases are written first and white box test cases later. To write black box test cases we need the requirement document and design or project plan. These documents are easily available at the initial start of the project. White box test cases cannot be started in the initial phase of the project because they need more architectural clarity which is not available at the start of the project. So normally white box test cases are written after black box test cases are written.

    29. Mention the basic components of defect report format.

    Ans:

    The basic components of defect report format include:

    • Project Name
    • Module Name
    • Defect detected on
    • Defect detected by
    • Defect ID and Name
    • Snapshot of the defect
    • Priority and Severity status
    • Defect resolved by
    • Defect resolved on

    30. Is Automation testing in agile methodology useful?

    Ans:

    Automation testing is very useful in agile methodology and helps in achieving maximum test coverage in a lesser time of the sprint.

    31. Which test cases can be automated?

    Ans:

    • Smoke test cases
    • Regression test cases
    • Complex calculation test cases
    • Data-driven test cases
    • Non-functional test cases

    32. On what basis you can map the success of Automation testing?

    Ans:

    By following criteria, the success of Automation testing can be mapped:

    • Defect Detection Ratio
    • Automation execution time and time savings to release the product
    • Reduction in Labour & other costs

    33. Explain Load Testing on websites?

    Ans:

    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.

    34. 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

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

     35. How to click on a hyperlink using linkText()?

    Ans:

    • driver.findElement(By.linkText(“Google”)).click();

    This command finds the element using link text and then clicks on that element. Thus, the user would be redirected to the corresponding page.

    Course Curriculum

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

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

    36. What is TestNG?

    Ans:

    It is an advanced framework which is designed in a way to leverage the benefits by both the developers and testers. It also has an inbuilt exception handling mechanism which lets the program to run without terminating unexpectedly.

    37. How to set test case priority in TestNG?

    Ans:

    Below code helps you to understand how to set test case priority in TestNG. 

    • package TestNG;
    • import org.testng.annotations.*;
    • public class SettingPriority {
    • @Test(priority=0)
    • public void method1() {
    • }
    • @Test(priority=0)
    • public void method1() {
    • }
    • @Test(priority=1)
    • public void method2() {
    • }
    • @Test(priority=2)
    • public void method3() {
    • }
    • }

    Test Execution Sequence:

    • Method 1
    • Method 2
    • Method 3

    38. Name some Junit extensions?

    Ans:

    Following are some of the JUnit extensions

    • Cactus
    • JWebUnit
    • XMLUnit
    • MockObject

    39. What is Object Repository? How can we create an Object Repository in Selenium?

    Ans:

    Object Repository refers to the collection of web elements belonging to Application Under Test (AUT) along with their locator values. With respect to Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

    40. How to input text in the text box using Selenium WebDriver?

    Ans:

    • By using sendKeys()method we can input the text in the text box using Selenium WebDriver.
    • Advance Level Software Testing Interview Questions

    41. 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. 

    42. How is the testing of ‘private’ methods 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 “protected” method.

    43. What is meant by Defect Cascading?

    Ans:

    Defect cascading is a defect which is caused by another defect. One defect triggers the other defect. When a defect is present in any stage but is not identified, hide to other phases without getting noticed. This will result in an increase in the number of defects.

    Let us understand this by an example.

    You are designing the Login Module of a WebPage:

    • In phase 1 – You are designing a Register User Module for Login and mobile number is mandatory but you can leave it blank due to a bug that gets unnoticed.
    • In Phase 2 – You will design the login form having username and password. The password is OTP which will be sent to User’s registered mobile number.

    Now as the Register module has a bug that mobile numbers can be left blank so this may lead to Login failure or maybe some system error or crash if a null mobile number is not handled. This is known as defect cascading.

    44. What are the different strategies for rollout to end users? 

    Ans:

    The strategies to be followed for rollout are as follows:

    • Pilot
    • Gradual Implementation
    • Phased Implementation
    • Parallel Implementation

    45. Explain how you can find broken links in a page using Selenium WebDriver?

    Ans:

    • This is a tricky question which the interviewer might present to you. He can provide a situation wherein there are 20 links in a web page, and we have to verify which of those 20 links are working and how many are not working (broken).
    • As you have to verify the working of every link, the workaround is that you need to send HTTP requests to all of the links on the web page and analyze the response. Whenever you use driver.get() method to navigate to a URL, it will respond with a status of 200 – OK. This indicates that the link is working and it has been obtained. Whereas any other status indicates that the link is broken.

    Let’s now understand how to do that.

    First, we have to use the anchor tags <a> to determine the different hyperlinks on the web page. For every <a> tag, we can use the attribute ‘href’ value to obtain the hyperlinks and then analyze the response received when used in driver.get() method.

    46. Which technique should be considered in the script “if there is neither frame id nor frame name”?

    Ans:

    If frame name and frame id is not available, then we can use frame by index. For example, there are 3 frames in a web page and if none of them have a frame name and frame id, then we can still select those frames by using frame (zero-based) index attribute. All the frames will have an index number like the first frame would be at index “0”, the second at index “1” and the third at index “2”.

    • driver.switchTo().frame(int arg0);

    47. How to take screenshots in Selenium WebDriver?

    Ans:

    By using the TakeScreenshot function you can take a screenshot. With the help of getScreenshotAs() method, you can simply save that screenshot.

    Example:

    • File scrFile = ((TakeScreenshot)driver).getScreenshotAs(outputType.FILE);

    48.  Explain how you will log in into any site if it is showing any authentication popup for username and password?

    Ans:

    If there is a pop up for logging in, we need to use the explicit command and verify if the alert is actually present. The below code helps you understand the use of explicit wait commands.

    • WebDriverWait wait = new WebDriverWait(driver, 10);
    • Alert alert = wait.until(ExpectedConditions.alertIsPresent());
    • alert.authenticateUsing(newUserAndPassword(**username**, **password**));

    49. How to skip a method or a code block in TestNG?

    Ans:

    To skip a particular test method or a code, then you can set the ‘enabled’ parameter in test annotation to false.

    • @Test(enabled = false)

    50. Briefly explain what does the below code snippet indicate?

    Ans:

    • WebElement sample = driver.findElement(By.xpath(“//*[contains(text(), ‘data’)]”));

    It defines a variable sample of type WebElement, and uses an XPath search to initialize it with a reference to an element that contains the text value “data”.

    This brings us to the end of this article on Top 50 Software Testing Interview Questions. Hope it helped in adding up to your knowledge. Wishing you all the best for your interview. Happy learning.

    51. Describe the important features of the JUnit framework?

    Ans:

    Important features of Junit are mentioned below

    • Junit is an open-source framework.
    • It Provides an annotation function to identify the suitable test methods.
    • It provides assertions function to test the expected results.
    • It provides test runners for running tests during development.
    • JUnit tests could be run automatically, and it can check its own results and also provide immediate feedback on code.
    • JUnit tests are organized into test suites that contain test cases and other test suites applications.
    • JUnit shows test progress if it is green then a test is going fine and if it turns red when a test fails.
    Course Curriculum

    Enroll in JUnit Training Course and Get Hired by TOP MNCs

    Weekday / Weekend BatchesSee Batch Details

    52. 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.

    53. 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.

    54. 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.
    • Part 2 – Junit Interview Questions (Advanced)

    55. How to create Parameterized tests?

    Ans:

    There are five steps to create Parameterized tests

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

    56. 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.

    57. What is Testing?

    Ans:

    Testing is the process of checking the functionality of the application whether it fulfills the requirement or not.

    58. What is unit testing?

    Ans:

    The process of testing individual functionality (known as a unit) of the application is called unit testing.

    59. 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.

    60. Give some disadvantages of manual testing.

    Ans:

    Following are some disadvantages of manual testing:

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

    61. 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.

    62. What are the features of JUnit?

    Ans:

    • Opensource
    • Annotation support for test cases
    • Assertion support for checking the expected result
    • Test runner support to execute the test case

    63. 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.

    64. What does XMLUnit provide?

    Ans:

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

    65. List the core components of Cactus.

    Ans:

    • Cactus Framework
    • Cactus Integration Module

    66. What are the methods in fixtures?

    Ans:

    • setup
    • tearDown

    67. What is the use of @Test annotation?

    Ans:

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

    68. 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.

    69. What are the important JUnit annotations?

    Ans:

    The test runner is used to execute the test cases.

    • Test
    • BeforeClass
    • Before
    • After
    • AfterClass

    70. What does Assert class?

    Ans:

    Assert class provides methods to test the test cases.

    71. 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
    Junit Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    72. Explain how you can write a simple JUnit test case?

    Ans:

    Determine a subclass of TestCase

    • To initialize object(s) under test, override the setup() method
    • To release object(s) under test override the teardown() method
    • Determine one or more public test XYZ() methods that exercise the objects under test and assert expected results.

    73. Mention what are parameterized tests?

    Ans:

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

    74. 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

    75. 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

    76. 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.

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

    Ans:

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

    • Set the CLASSPATH
    • Invoke the runner

    78. 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.

    79. 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:

    • @acteadminBeforeClass
    • 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.

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

    Ans:

    • @After annotation:

    syntax:

    • @After
    • public void myMethod()

    This method should execute 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.

    81. 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.

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

    Ans:

    First set the ClassPath as follows:

    • set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar

    Invoke JunitCore

    • java org.junit.runner.JUnitCore

    83. 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.

    84. 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.

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

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

    Ans:

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

    86. 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.

    87. 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.

    88. 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

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

    Ans:

    • @Test (expected = Exception.class)

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

    90. What are the disadvantages of manual testing?

    Ans:

    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.

    91. 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.

    92. What are important features of JUnit?

    Ans:

    Following are the important features of JUnit

    • It is an open source framework.
    • Provides Annotation to identify the test methods.
    • Provides Assertions for testing expected results.
    • Provides Test runners for running tests.
    • JUnit tests can be run automatically and they check their own results and provide immediate feedback.
    • JUnit tests can be organized into test suites containing test cases and even other test suites.
    • JUnit shows test progress in a bar that is green if test is going fine and it turns red when a test fails.

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

    Ans:

    @Test(expected={exception class}.

    For example: @Test(expected=IllegalArgumentException.class) 

    94.  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

    95. 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.

    96. How to install JUnit?

    Ans:

    Follow the steps below

    • Download the latest version of JUnit, referred to below as junit.zip.
    • Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
    • Add JUnit to the classpath
    • set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar
    • 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).
    • Then simply type − java org.junit.runner.JUnitCore org.junit.tests.AllTests

    All the tests should pass with an “OK” message. If the tests don’t pass, verify that junit.jar is in the CLASSPATH.

    97. 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.

    98. In Java, assert is a keyword. Won’t this conflict with JUnit’s assert() 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.

    99. 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.

    100. 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

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free