JUnit interview questions and answers

  1. What is JUnit?
    Answer: JUnit is an open source testing framework for the java programming language. The test cases are written in java. Test-driven development is the ideal way to create a bug free code.
  2. How to write a Junit test class?
    Answer: Follow the below steps to write a test case:
    • The test class should extend TestCase class.
    • Define a method setUp() and initialize all the objects in that method. This setUp() method should be overridden.
    • Define a method tearDown() and release all the objects. This tearDown() method should also be overridden.
    • For each method, one or more test cases or test methods are written depending on the logic of the method.
  3. What is JUnit TestSuite?
    Answer: JUnit TestSuite is a composite of tests. The TestSuite is a container class under package junit.framework.TestSuite. TestSuite runs a collection of test cases. In JUnit, both @RunWith and @Suite annotation are used to run the suite test.
  4. What are Parameterized tests?
    Answer: Parameterized tests allow user or developer to run the same test over and over again using different values.
  5. What happens if a JUnit Test Method is declared as "private"?
    Answer: If a JUnit test method is declared as private, then the compilation would be successful, but the execution of the test method would fail. This is because JUnit requires all the test methods to be declared as "public" and the return type should be "void"
  6. How do you test a “private” method?
    Answer: "private" methods can only be accessed from the same class. No other class will have any access to the private method. Hence developer has to test the private methods manually.
  7. How can we test a method that do not return anything?
    Answer: There are some ways we can write test case for the methods which do not return anything. The way test cases are written depends on the logic of the method. For example.
    • A method may take parameters and then modify the values or variables of an object.
    • A method may modify values in a file or in a database.
    • A method may change values of static variables.
  8. How do you test a method that throws desired exceptions?
    Answer: Add the optional expected attribute to the @Test annotation. The following is an example test that passes when the expected FileNotFoundException is raised: "@Test(expected=FileNotFoundException.class)"

1 comment:

  1. 6 How do you test a “private” method?
    We can use reflection for testing private methods but more correct way test over public method plus check it by code coverage tools.

    ReplyDelete