JUnit & Mockito Interview Questions
Published on

JUnit & Mockito Interview Questions

Authors

JUnit

What is unit testing?

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

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

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

What are the features of JUnit?

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

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

The test class is declared in the same package as the target class.

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

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

Can there be more than one main method in a Java Program?

Yes, you can have as many main methods as you like. For example, you can have main methods with different signatures from the main(String[]) called overloading, and the JVM will ignore those main methods.

You can have one public static void main(String[] args) method in each class. Some people use those methods for testing. They can test the operation of each class individually. The JVM will only invoke the public static void main(String[] args) method in the class you name when you write java Class1.

public class Class1{
    public static void main(String args1[])
    {
        System.out.println("Hello Class1");

    }
}

public class Class2{
    public static void main(String args2[])
    {
        System.out.println("Hello Class2");

    }
}

The only way to have two main methods is by having two different classes, each with one main method. The name of the class you use to invoke the JVM (e.g., java Class1, java Class2) determines which main method is called.

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

Yes

Why Not Just Write a main() Method for Unit Testing?

It is possible to write a main() method in each class that needs to be tested for unit testing. In the main() method, you could create a test object of the class, For example, and write some tests to test its methods.

  • If one method call fails, the following method calls won’t be executed. You will have to work around this.
  • Your classes will be cluttered with test code in the main method. Finally, all those test codes will be packaged into the final product.
  • If you want to log the results of tests in HTML format or text format, you will have to write additional code.

What Is a JUnit Test Fixture?

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

What Is JUnit TestSuite?

JUnit TestSuite is a container class, junit.framework.TestSuite, used in JUnit 3.8, allows you to group multiple test cases into a collection and run them together.

What are the methods in fixtures?

  • setup
  • tearDown

What are the essential JUnit annotations?

  • @Test
  • @BeforeClass
  • @Before
  • @After
  • @AfterClass

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

No, it depends on how complex or if there are chances of error in that class.

What is code coverage in JUnit?

Code coverage means measuring how much of your code is executed during your unit tests. Basically, after running your unit tests, you get a report showing you how many percent of the code was executed during the tests and what lines precisely were executed.

What Happens If a JUnit Test Method Is Declared as “private”?

If a JUnit test method is declared as “private”, the compilation will pass ok. But the execution will fail. This is because JUnit requires that all test methods be declared as “public” as it runs the methods in runtime using a test runner.

As cyclomatic code complexity is determined based on several decision points within the code and hence execution paths, higher cyclomatic complexity makes it challenging to achieve test/code coverage.

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

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

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

Name some code smells which make it hard to achieve high code coverage?

Long method, Large conditionals

What happens if a test method throws an exception?

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

What is a JUnit parameterized test?

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.

Mockito

What are the top advantages of mocking?

  • Verify interactions
  • Test the block of code in isolation

When and why should a spy be used?

Spy is a type of partial mock supported by Mockito.

  • When no mock is set up, any interaction on spy results in calling the real methods. But it still allows you to verify the interactions with the spied object like – was a method called, how many times the method was called, the arguments using which the method was called, etc.
  • It gives you the flexibility to set up partial mocks.

Why can’t static methods be mocked using Mockito?

Static methods are associated with the class itself and not any particular instance of the class. This means that all instances/objects of the class use the same instance of the static method.

Mock libraries typically create mocks by dynamical instance creation at runtime, either through interfaces or through inheritance. However, as the static method is not associated with any particular instance, it’s not possible for mocking frameworks (like Mockito, easy mock, etc.) to mock Static methods.

What is an excellent testable code?

  • Reduced no of dependencies or tight coupling – Example: Dependencies should be injected rather than instantiated directly.
  • Code that adheres to SRP (Single Responsibility Principle) – This essentially means that the class should not have multiple reasons to change. Adherence to SRP avoids classes creating dependency on itself and keeps the code cohesive and clean.
  • Less / Minimal usage of static methods and final classes – These generally indicate code smells and mainly were associated with the legacy code.

Which frameworks can support mocking Private and Static methods?

Frameworks like PowerMockito (extensions of Mockito framework), JMockit, etc., do provide means to mock private and static methods.

Explain about Poxy-based vs. Bytecode-based Mocking frameworks?

Proxy-basedBytecode based
SimplicityMore simple and easy to useIt might involve complex mock setup logic
Mode of creation

A proxy or fake object which does not require an instance of class/interface is created

It essentially involves creating objects and, at runtime, manipulates the instances for the mocked/stubbed behavior

FunctionalityMocking classes and interfaces

In addition to classes and interfaces, it allows mocking static methods, final classes, etc.

Java dependencyNot very tightly coupled to Java versions

Since these frameworks involve bytecode manipulation, they are tightly coupled and might not be backward/forward compatible across java versions.

ExamplesMockito, EasyMock, etc.PowerMock, JMockit, etc.

What is Exploratory Testing?

“Exploratory testing” – as the name suggests, is simultaneous learning, test design, and test execution process. Thus, we can say that in this testing: test planning, analysis, design, and test execution, are all done together and instantly.

This testing is about exploring the system and encouraging real-time and practical thinking of a tester.

Is Mockito Thread-safe?

For healthy scenarios Mockito plays nicely with threads. For instance, you can run tests in parallel to speed up the build. Also, you can let multiple threads call methods on a shared mock to test in concurrent conditions. Check out a timeout() feature for testing concurrency.

However Mockito is only thread-safe in healthy tests, that is tests without multiple threads stubbing/verifying a shared mock. Stubbing or verification of a shared mock from different threads is NOT the proper way of testing because it will always lead to intermittent behavior. In general, mutable state + assertions in multi-threaded environment lead to random results. If you do stub/verify a shared mock across threads you will face occasional exceptions like: WrongTypeOfReturnValue, etc.

What is Law of Demeter?

It can be explained as principle of least knowledge.

  • Each unit should have only limited knowledge about other units: only units “closely” related to the current unit.
  • Each unit should only talk to its friends; shouldn’t talk to strangers.
  • Only talk to your immediate friends.