2023 Top JUnit Interview Questions - IQCode

JUnit Interview Questions for Freshers

1. What is JUnit?

JUnit is an open-source unit testing framework for Java programming language. It is used to write and run test cases to ensure that the codes are working as expected. It supports annotations for identifying test methods and expected results. JUnit helps in identifying bugs in the source code in early stages, which makes the software development process more efficient and faster.

Overview of Unit Testing

Unit Testing is a software testing technique that verifies individual modules or components of a larger software program. It ensures that each module or component is working as expected and produces the desired results. The main aim of unit testing is to isolate each part of the software program and prove that they are correct and bug-free. Unit testing is a critical activity in the software development life cycle, as it helps detect and fix errors early, making the software more reliable and less prone to defects.

Why Use JUnit and Who Uses it More: Developers or Testers?

JUnit is a popular Java-based testing framework used to perform unit testing. We use JUnit to ensure that our code works as intended and to detect bugs as early as possible in the development process. It is mainly used to test small, isolated pieces of code, known as units, to ensure that they function correctly.

Both developers and testers make use of JUnit to ensure that their code meets the desired specifications. Developers use it to test their own code before submitting it for integration testing, while testers use it to ensure that the code meets the expected functionality requirements.

In general, developers use JUnit more frequently than testers, as it falls under the category of developer testing. However, the ultimate goal is to work together as a team to improve the quality of the software being developed and ensure its success.

Features of JUnit

JUnit is a popular testing framework for Java. It provides the following features:

  • Annotation support: JUnit makes use of annotations such as @Test, @Before, and @After to mark the methods that need to be executed during testing.
  • Assertions: JUnit provides a set of assertion methods that can be used to check if the expected result matches the actual result.
  • Parameterized testing: JUnit allows for parameterized testing, which means that the test case can be executed with multiple sets of input parameters.
  • Suites: JUnit enables grouping of test cases into suites, which helps in organizing and executing test cases.
  • Exception handling: JUnit provides support for testing exception handling in a method.
  • Integration: JUnit can be easily integrated with build tools such as Ant and Maven to automate the testing process.
// Sample code using JUnit

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MyClassTest {

   public void testAdd() { 
      MyClass myClass = new MyClass();
      int result = myClass.add(3, 4);
      assertEquals(7, result);

In the above code, we can see that the @Test annotation is used to mark the test method, and the assertEquals method is used to check if the expected and actual results match.

Is it Necessary to Write Test Cases for Every Logic?

In software development, writing test cases for every piece of code is considered a good practice, as it ensures that the code behaves as expected and meets the requirements. However, whether or not to write test cases for every logic depends on the complexity and criticality of the code.

For simple or straightforward code, writing a test case for every logic may not be necessary, as the code can be easily reviewed manually. On the other hand, for complex and critical code, writing test cases for every logic is absolutely necessary to ensure that the code performs as intended and that any future changes do not unintentionally break the existing functionality.

In short, while it may not always be mandatory to write test cases for every logic, it is still advisable to do so in order to maintain the quality and reliability of your code.

Important annotations in JUnit

JUnit provides several important annotations to help with creating and running tests:

- @Test: This annotation identifies a test method that should be run by JUnit. - @Before: This annotation indicates that the method annotated with it should be run before each test method in the class. - @After: This annotation indicates that the method annotated with it should be run after each test method in the class. - @BeforeClass: This annotation indicates that the method annotated with it should be run once before all test methods in the class. - @AfterClass: This annotation indicates that the method annotated with it should be run once after all test methods in the class. - @Ignore: This annotation indicates that the test method should be ignored by JUnit.

Writing a Simple JUnit Test Case

In Java, JUnit is a unit testing framework that allows developers to write and run tests. A JUnit test case is a method that checks if a part of the code works as expected. Here's how you can write a simple JUnit test case:

import static org.junit.Assert.assertEquals; import org.junit.Test;

public class CalculatorTest {

@Test public void testAdd() { Calculator calculator = new Calculator(); int result = calculator.add(2, 3); assertEquals(5, result); } }

In this example, we are testing the add() method of the Calculator class. We create an instance of the Calculator class and call the add() method with two arguments 2 and 3. We then use the assertEquals() method to assert that the expected result is equal to the actual result.

Make sure you have JUnit installed in your project before running the test case. You can then run the test case and check if it passes or fails.

Consequences of Setting the Return Type of a JUnit Method as String

If the return type of a JUnit method is set to String, it may cause issues with the test assertions. The test assertion methods provided by JUnit, such as assertEquals(), expect an actual value and an expected value to compare. If the return type of the test method is String, these assertion methods will not be able to compare the returned value with the expected value correctly.

Additionally, setting the return type of a JUnit method as String may complicate the testing process. String values can be easily manipulated and may have unexpected values, making test debugging difficult.

Therefore, it is recommended to set the return type of JUnit test methods as void as they do not need to return anything.

Understanding the Importance of @Test Annotation

In the context of unit testing using frameworks like JUnit, the @Test annotation is crucial. It marks a method as a test method, which can be run by the JUnit framework. The @Test annotation helps in the identification of test methods that need to be executed during the testing process.

Without the @Test annotation, JUnit won't be able to recognize the method as a test method, and it won't run the code inside it as part of the testing process. Hence, the @Test annotation plays a significant role in enabling developers to implement effective unit testing and improve the quality of their code.

Understanding JUnit Fixtures

A JUnit fixture is a fixed set of conditions used as a baseline for running unit tests. It includes the preparation of necessary objects, setting up of required parameters, and performing other activities required to ensure that test cases are executed under a controlled environment with consistent and predictable results. Fixtures help to ensure that tests run reliably and are repeatable, even if changes are made to the system being tested. Essentially, fixtures are the foundation upon which JUnit test cases are built.

What is a Test Suite?

A test suite is a collection of test cases that are designed to test a specific behavior or functionality of a software application. It is a comprehensive approach to testing the software. Test suites help to ensure that the software performs as expected and meets the required standards. They are used to verify and validate the functionality of the software and to identify any defects or errors that may exist.

Mocking and Stubbing: An Explanation

Mocking and stubbing are techniques used in unit testing to simulate the behavior of components that a code unit depends on. Mocking involves creating a fake object that represents the behavior of the real object, while stubbing involves creating a simpler, pre-defined object that returns specific results when called. Both techniques aim to isolate the code unit being tested and ensure that it functions correctly, even if the dependent components are not yet available or have not been fully implemented.

JUnit Assert Methods

JUnit assert methods are a set of methods provided by JUnit framework to perform assertions in testing. These methods allow developers to validate actual test conditions against expected results. Commonly used JUnit assert methods include:

- `assertEquals()`: This method compares the expected result with the actual result, testing for equality. - `assertFalse()`: This method expects the result to be false. - `assertTrue()`: This method expects the result to be true. - `assertNotNull()`: This method expects the result to be not null. - `assertNull()`: This method expects the result to be null.

These JUnit assert methods help in creating effective and reliable unit tests, ensuring that each piece of code functions as expected.

Importance of @RunWith Annotation in JUnit Testing

In JUnit testing, the @RunWith annotation is used to specify the test runner class that will execute the test cases. It is important because different test runners may have different ways of executing test cases and generating test results. By using the @RunWith annotation, the desired test runner can be explicitly specified, allowing for consistent and reliable test execution and reporting.

For example, if you want to use JUnit with Spring, you can use the @RunWith(SpringJUnit4ClassRunner.class) annotation to specify the Spring test runner. This will allow you to take advantage of Spring's dependency injection and other features in your test cases.

Overall, the @RunWith annotation is an important tool in JUnit testing that helps ensure consistent and accurate test results.

JUnit's Contribution to Achieving Test Isolation

JUnit is a popular Java testing framework that provides various features for testing Java applications. One of the significant contributions of JUnit to testing is achieving test isolation.

JUnit helps achieve test isolation by executing each test method within a separate JVM (Java Virtual Machine). By doing so, it ensures that any side effects of the tests are isolated and does not affect other tests, thus ensuring the reliability and accuracy of test results.

Additionally, JUnit provides the @Before and @After annotations to help prepare and clean up test fixtures before and after each test method is executed. This also helps ensure test isolation by preventing any shared state between tests that could lead to unexpected behavior.

Overall, JUnit's features and best practices promote test isolation and enable developers to write reliable and effective unit tests for their Java applications.

Best Practices for Writing JUnit Test Cases

When writing JUnit test cases, following are the best practices:

- Test only one piece of functionality per test case to keep it simple and clear.
- Use naming conventions for test methods that are easy to understand and describe the functionality being tested.
- Write test cases for both positive and negative scenarios.
- Use assertions to validate the expected results of the test case.
- Use setUp() and tearDown() methods to set up the test environment and clean up after the test.
- Use parameterized tests when multiple inputs or outputs are involved.
- Mock objects when necessary to isolate the code being tested.
- Keep the tests independent of one another and avoid dependencies between them.

Following these best practices will help ensure that the JUnit test cases are effective in catching bugs and preventing regressions.

Differences between JUnit 4 and JUnit 5

JUnit is a testing framework for the Java programming language. JUnit 4 and JUnit 5 are two different versions of the framework. There are several differences between these two versions:

1. Annotations: In JUnit 4, annotations such as "@Test" and "@Before" were used for test cases and setup/teardown methods, respectively. However, in JUnit 5, these annotations have been replaced with "@Test" and "@BeforeEach"/"@AfterEach" annotations.

2. Platform: JUnit 4 can only be used for testing Java 5 and above, while JUnit 5 can be used for testing Java 8 and above. Additionally, JUnit 5 is modular, which means that it can be used with other testing frameworks.

3. Test Execution: JUnit 5 allows the execution of tests in parallel, which greatly reduces the execution time for large test suites. JUnit 4 executes tests sequentially.

4. Assertions: JUnit 5 provides more assertion methods than JUnit 4. For example, JUnit 5 provides the "assertAll()" method, which allows multiple assertions to be made in a single test case.

5. Architecture: JUnit 5 has a more modular architecture compared to JUnit 4. This allows for more flexibility and easier maintenance.

Overall, JUnit 5 is a more modern and flexible testing framework compared to JUnit 4. It provides new features and enhancements that make testing easier and more efficient.

Differences between JUnit and TestNG

JUnit and TestNG are both popular testing frameworks used in Java development. However, there are some differences between them:

  • TestNG supports more annotations than JUnit, making it more flexible for organizing and configuring tests.
  • TestNG allows for more customization of test suites, including the ability to define dependencies between test methods.
  • JUnit provides better integration with development tools such as Eclipse and IntelliJ IDEA.
  • TestNG allows for parallel execution of tests, which can significantly improve testing time.
  • JUnit has been around longer and has a larger community of users and resources.

Ultimately, the choice between JUnit and TestNG depends on the specific needs of the project and team preferences.

  // Example of JUnit test
  import org.junit.Test;

  public class MyTests {

    public void testMethod() {
      // test logic here


  // Example of TestNG test
  import org.testng.annotations.Test;

  public class MyTests {

    public void testMethod() {
      // test logic here


Ignoring Tests in JUnit

In JUnit, test cases can be ignored by annotating the test method with the `@Ignore` annotation. This can be useful when a test case is failing due to external factors, such as a network resource being unavailable.

To ignore a test in JUnit, simply add the `@Ignore` annotation before the test method as shown in the example below:

@Ignore("This test is currently not working")
public void testSomething() {
    // test code

In this example, the test `testSomething()` is being ignored with a message indicating that it is not working at the moment. When you run your test suite, this particular test will be skipped.

It's important to note that it's generally not a good idea to leave ignored tests in your codebase for extended periods of time. Ignored tests can often indicate areas where your code may need improvement or refactoring, and it's best to address these issues as soon as possible.H3. Purpose of @Before and @After Annotations in JUnit 4

In JUnit 4, the annotations @Before and @After are used to define methods that will be executed before and after each test method in a test class.

The @Before annotated method is executed before each test method and is typically used to set up any necessary objects or data for the tests.

Similarly, the @After annotated method is executed after each test method and is used to clean up any resources that were used during the tests.

By using these annotations, the setup and teardown operations can be automated, making the test code more efficient and less error-prone.

Testing Protected Methods in Java

In Java, protected methods are accessible within the same package or through inheritance in a subclass. Testing protected methods in Java can be done through the following steps:

1. Create a subclass in the same package as the original class containing the protected method. 2. From within the subclass, call the protected method to test its functionality. 3. Alternatively, you can create a mock object using a framework such as Mockito to test the protected method without needing to create a subclass.

It's important to note that testing protected methods can be controversial, as some argue that it should only be tested indirectly through the public methods that use it. However, in certain situations, it may be necessary to test the protected method directly for proper functionality.

Why is System.out.println() not recommended for testing and debugging?

The use of System.out.println() is not recommended for testing and debugging because it can be difficult to find and remove these statements from the code afterwards. Additionally, it can be time-consuming to add and remove print statements manually when debugging.

A better alternative is to use a dedicated debugging framework like Log4j or SLF4J. These frameworks allow developers to log messages at different levels of severity, and provide more control over when and where the messages are logged. Additionally, they allow developers to easily enable or disable logging statements, making it easier to manage the amount of output produced during testing and debugging.

Running JUnit from Command Line

JUnit can be executed from the command line using the


command and passing the JUnit jar file and the test class name.

The basic syntax is:

java -cp junit-4.XX.jar;test_classes_folder org.junit.runner.JUnitCore TestClass1 TestClass2 ...



with the appropriate JUnit version and


with the path to the folder containing the test classes. Replace




, etc. with the names of the test classes you want to run.


java -cp junit-4.13.jar;./tests org.junit.runner.JUnitCore CalculatorTest

This command will run the


class located in the


folder using JUnit version 4.13.

Note: If you have multiple test classes, separate them with spaces.

Asserting Exceptions in JUnit 4 Tests

In JUnit 4, you can use the `@Test` annotation with the `expected` parameter to assert that a specific exception is thrown by a method during a unit test. Here is an example:

@Test(expected = IllegalArgumentException.class) public void testMethod() { // Call the method that should throw the exception someObject.methodThatThrowsIllegalArgumentException(); }

In this example, the `@Test` annotation is used with the `expected` parameter to specify that the `testMethod` should throw an `IllegalArgumentException`. If the method does not throw the exception or throws a different exception, then the test will fail.

It is important to note that this technique can only be used to assert that a single exception is thrown. If you need to assert that a method throws one of several exceptions, or if you need to assert other details about the exception (such as the message or cause), then you will need to use a different technique, such as a try-catch block.

Differences between @Before, @After, @BeforeClass and @AfterClass

In JUnit, the '@Before' and '@After' annotations are used to set up and tear down the test fixtures, respectively, whereas the '@BeforeClass' and '@AfterClass' annotations are used for methods that are executed only once for the entire test class.

@Before: This annotation is used to specify a method that should be executed before each test method in the test class is run. This is useful for setting up common objects or data used by the test methods.

@After: This annotation is used to specify a method that should be executed after each test method in the test class is run. This is useful for cleaning up objects or data that were used during the test methods.

@BeforeClass: This annotation is used to specify a method that should be executed only once before any of the test methods in the test class are run. This is useful for setting up resources that are shared across all test methods in the class.

@AfterClass: This annotation is used to specify a method that should be executed only once after all test methods in the test class have been run. This is useful for cleaning up resources that were used throughout the entire test class.

It should be noted that the methods annotated with '@BeforeClass' and '@AfterClass' must be declared as public and static.

Explanation of Hamcrest Matchers

Hamcrest Matchers are a set of Java libraries that provide a way to write clear and expressive tests. They allow developers to write assertions that are more readable and maintainable than traditional JUnit assertions. Matchers help to eliminate boilerplate code and make tests more concise. Some examples of Hamcrest Matchers include comparing object properties, asserting the type of an object, and checking the size of a collection. Overall, Hamcrest Matchers are a useful tool for creating effective unit tests.

Relationship between Cyclomatic Complexity of Code and Unit Tests

In software engineering, the cyclomatic complexity is a measure of the number of independent paths in a program's source code. It is an indicator of how difficult the code is to understand and maintain. Unit tests, on the other hand, are automated tests that are designed to check individual pieces of code to ensure that they work as expected.

There is a strong relationship between the cyclomatic complexity of code and the need for unit tests. As the complexity of the code increases, the number of possible paths through the code also increases, making it more difficult to ensure that all possible scenarios have been tested. This makes unit tests even more essential to ensure that the code is working properly.

In general, it is good practice to keep the cyclomatic complexity of code low to reduce the complexity of potential unit tests. This can be achieved by using simple and straightforward coding techniques, such as breaking large functions into smaller, more manageable pieces. By reducing the complexity of the code, unit testing can be made more effective and efficient.

Keyboard Shortcut for Running JUnit Test Cases in Eclipse IDE

To run JUnit test cases in Eclipse IDE, you can use the following keyboard shortcut:

Ctrl + Shift + F11

This will run the currently open test file in the Eclipse IDE. If you want to run a specific test method within the file, simply place your cursor within that test method and use the same shortcut.

Using keyboard shortcuts in Eclipse can help you save time and be more productive in your development workflow.

Definition and Types of Code Coverage

Code coverage is a measure used to determine what portion of an application's source code is being exercised by automated tests. Simply put, it measures the extent to which the application's code is being tested by the test cases. A higher code coverage implies that more of the code is being tested, and a lower code coverage implies the opposite.

There are several types of code coverage:

  • Statement coverage: This measures the number of individual statements in the code that are executed by a test case.
  • Branch coverage: This measures the number of branches or decision points within the code that were executed by a test case.
  • Function coverage: This measures the number of functions or methods in the code that were executed by a test case.
  • Line coverage: This measures the number of lines of code that were executed by a test case.

Overall, measuring code coverage is an essential aspect of software development. It enables developers to identify areas of code that need additional testing and refinement, ultimately leading to more robust and stable applications.

Note: Code coverage data helps developer to find untested coding line or block so that they can test those codes and make software more reliable and bug-free. 

Testing for Timeout in JUnit Java Method

Yes, it is possible to test for a timeout in JUnit java method using the `@Test(timeout)` annotation. This annotation allows you to specify the maximum time that a test method should take to execute. If the method takes longer than the specified time, the test will fail with a `java.util.concurrent.TimeoutException`.

Here is an example:

@Test(timeout = 100)
public void testMethod() {
    // test code here

In the example above, the test will fail if the `testMethod()` takes longer than 100 milliseconds to execute. It is important to note that the specified time limit should be reasonable based on the task that the method is performing.

Best Practices for Writing Testable Code

Writing testable code is essential for creating high-quality software. Here are some best practices to follow when writing code to make it more testable:

1. Keep functions and methods small and modular. 2. Separate concerns and keep your code organized. 3. Avoid global state and mutable data. 4. Use dependency injection for better decoupling. 5. Write unit tests for each function or method. 6. Use mocking frameworks to isolate code dependencies. 7. Use code coverage tools to measure test effectiveness. 8. Automate your testing process as much as possible.

By following these best practices, you can write testable code that is easier to maintain and update over time.

Why JUnit Only Reports the First Failure in a Single Attempt?

JUnit is designed to report failures in a test method one at a time. When a failure occurs, JUnit stops the test method and reports that failure. This is done to ensure that the user can fix and re-run the test method without being overwhelmed with multiple failure reports.

If the test method were to continue running after the first failure, it is possible that subsequent failures could occur due to the initial failure. This would not only make it difficult to pinpoint the root cause of the failures, but also make it harder to fix them.

Therefore, JUnit only reports the first failure in a single attempt to help the user focus on fixing one problem at a time. If the user re-runs the test method after fixing the first failure, JUnit will report any additional failures that occur.

How to Test Private Methods?

In general, it is not recommended to test private methods directly because they are not part of the public interface of a class. However, if testing a private method is absolutely necessary, there are a few ways to do it:

1. Use Reflection: Java provides a way to reflectively access private members of a class, including private methods. This approach involves using the reflection API to create an instance of the class, and invoking the private method using reflection.

2. Make Method Public: Another option is to make the private method package-private or public, depending on the level of visibility required. This approach is often the easiest, but it can lead to a cluttered public interface if not managed properly.

3. Test Through Public Methods: If the private method is used only by public methods, then testing the public methods that use it should exercise the private method indirectly.

It is important to note that testing private methods may not always be the best approach to unit testing, and it is often better to test the behavior of a class through its public interface.

Testing a Generics Class

When testing a generics class, you can create test cases for different types of data and ensure that the class works as expected for all of them. For example, if you have a list class that uses generics, you can test it by creating instances of the list with different data types and performing operations like adding, removing, and searching for items. You can also test edge cases, such as when the list is empty or when it contains duplicate items. By testing the class thoroughly with different types of data, you can ensure that it is working as expected and that it is a robust solution to your problem. Code testing should be done with the appropriate testing framework in your programming language.

JUnit and Mockito Interview Questions

One of the commonly asked questions in unit testing is:

Why do we need mocking in unit testing?

Mocking is important in unit testing because it allows us to isolate the behavior of a single unit from the behavior of its dependencies. This allows us to test our code in isolation and to easily identify bugs in the code. By creating mock objects that simulate the behavior of dependencies, we can control the input to the code under test and verify that it behaves correctly under different conditions.

Mocking is particularly useful when dealing with external dependencies such as databases, web services, or other components that are outside of our control. By creating mock replacements for these dependencies, we can test our code without requiring access to the real dependencies, which can be slow, unreliable, or inaccessible in certain situations.

With mocking, we can also test edge cases and error conditions that are difficult to reproduce in a live system. By simulating different scenarios with mock objects, we can verify that our code behaves correctly under all possible conditions.

Overall, mocking is an essential technique for unit testing that enables us to write better, more reliable code with fewer bugs.

// Sample code demonstrating the use of mocking with Mockito
public class UserServiceTest {

   private UserDao userDao;
   private UserService userService;
   public void setUp() {
       userDao = mock(UserDao.class);
       userService = new UserService(userDao);
   public void testGetUserById() {
       // Create a mock User object
       User user = new User(1, "John", "Doe");
       // Tell the mock object what to do when getUserById is called
       // Call the getUserById method on the UserService object, which will use the mocked UserDao
       User result = userService.getUserById(1);
       // Verify that the mocked UserDao was called correctly
       // Verify that the result is what we expect
       assertEquals(user, result);


Mockito is a popular Java mocking framework that allows developers to create and test code in an isolated environment. The main advantage of Mockito is that it simplifies testing by providing a way to create mock objects that mimic the behavior of real objects in your system. This makes it easier to test code that has dependencies, such as database connections or external APIs, without having to actually connect to those resources during testing.

Some of the advantages of using Mockito include: - Faster testing: Mockito allows developers to test their code more quickly by providing a way to create mock objects without having to write complex testing code. - Easy to use: Mockito is easy to learn and use, even for developers who are new to testing. - Flexible: Mockito provides a lot of flexibility in terms of how you can create and configure mock objects. This makes it easier to test a wide range of scenarios and edge cases. - Supports a wide range of testing frameworks: Mockito is compatible with a range of testing frameworks, including JUnit and TestNG, making it easy to integrate into your existing testing workflow.

When and Why Should We Use Spy?

As a software developer, there are scenarios where you may need to test how a particular function or method is called, how many times it is called, and with which arguments. In such circumstances, you can use a testing technique called "spying."

The concept behind spying is to create a mock function that records all its calls in an array, so you can access the array afterwards to check how the function was called and with what parameters. Spies come in handy when dealing with situations where the function implementation is not easily testable.

However, it is crucial to use spy judiciously because overuse can lead to code that is over-engineered and difficult to maintain. Therefore, spies are best used in specific scenarios such as testing complex network protocols or dealing with asynchronous code.

Understanding the Difference between thenReturn() and doReturn() in Mockito

In Mockito, both thenReturn() and doReturn() are used to set return values for mocked methods, but there is a subtle difference between the two.

thenReturn(): This method sets the value to be returned by the mocked method when it is called. It is typically used for methods that return a value.

doReturn(): This method sets the value to be returned by the mocked method, but it does not actually invoke the method. It is generally used for methods that return void.

The main difference between these methods is that thenReturn() invokes the mocked method, whereas doReturn() does not. So, if the method being mocked is throwing an exception or has a side effect that needs to be suppressed, then doReturn() should be used instead of thenReturn().

Here's an example:


Suppose we have a basic interface "Calculator" with a method "add". We want to mock this method and return the sum of two integers.

public interface Calculator { 
     int add(int num1, int num2); 

We can mock the add method and return the sum of the two numbers as follows:

Calculator mockCalculator = mock(Calculator.class);

If we want to use doReturn() instead, we can do it like this:


In this case, we don't need to call thenReturn(), because doReturn() is enough to set the return value for the mocked method.

In summary, thenReturn() is used to set the return value for methods that return a value, while doReturn() is used for methods that do not return a value.H3 tag: Main difference between @Mock and @InjectMocks

The main difference between @Mock and @InjectMocks is that @Mock is used to create a mock object of a class or interface, while @InjectMocks is used to inject those mock objects into the class under test. In other words, @Mock creates the mock objects, while @InjectMocks injects them into the appropriate places in the code.

Why is it not possible to mock static methods in Mockito?

The Mockito framework does not support mocking of static methods. This is because static methods are bound to their class instead of a specific instance, which makes it difficult for Mockito to create a proxy for them.

It is generally recommended to avoid the use of static methods in testable code, as they can lead to tight coupling and make it difficult to isolate and test individual components. Instead, consider using dependency injection and designing your code in a more modular and testable way.

//Example of using a static method
public class MathUtils {
    public static int add(int a, int b) {
        return a + b;

//Better approach using dependency injection
public class MathUtils {
    public int add(int a, int b) {
        return a + b;

public class Calculator {
    private MathUtils mathUtils;

    public Calculator(MathUtils mathUtils) {
        this.mathUtils = mathUtils;

    public int add(int a, int b) {
        return mathUtils.add(a, b);

Mocking Void Methods with Mockito

In Mockito, mocking void methods is quite similar to mocking methods that return a value. You can use the `doNothing()` method to mock void methods. Here's an example:


// Create a mock object
MyClass myObj = Mockito.mock(MyClass.class);

// Call a void method on the mock object

// Perform some operations
// ...

// Verify that the void method was called
Mockito.verify(myObj, Mockito.times(1)).someVoidMethod();

In the example above, we create a mock object of `MyClass`. We then mock the `someVoidMethod()` method using `doNothing()`. This method tells Mockito to do nothing when `someVoidMethod()` is called.

We then perform some operations on the object, and finally we verify that the `someVoidMethod()` method was called exactly once using `verify()`.

Technical Interview Guides

Here are guides for technical interviews, categorized from introductory to advanced levels.

View All

Best MCQ

As part of their written examination, numerous tech companies necessitate candidates to complete multiple-choice questions (MCQs) assessing their technical aptitude.

View MCQ's
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.