Bird
Raised Fist0
JUnittesting~20 mins

Mocking void methods in JUnit - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Void Method Mocking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of mocking a void method with doNothing()
What will be the output of the following JUnit test using Mockito when the void method is mocked with doNothing()?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class Service {
    void performAction() {
        System.out.println("Action performed");
    }
}

public class ServiceTest {
    @Test
    void testPerformAction() {
        Service mockService = mock(Service.class);
        doNothing().when(mockService).performAction();
        mockService.performAction();
        System.out.println("Test completed");
    }
}
AAction performed\nTest completed
BNo output
CNullPointerException
DTest completed
Attempts:
2 left
💡 Hint
Think about what doNothing() does when mocking void methods.
❓ assertion
intermediate
2:00remaining
Correct assertion to verify a void method call
Which assertion correctly verifies that a void method performAction() was called exactly once on a mock object in JUnit with Mockito?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class Service {
    void performAction() {}
}

public class ServiceTest {
    @Test
    void testVerifyCall() {
        Service mockService = mock(Service.class);
        mockService.performAction();
        // Which assertion is correct here?
    }
}
Averify(mockService).performAction(1);
BassertTrue(mockService.performAction());
Cverify(mockService, times(1)).performAction();
DassertEquals(1, mockService.performAction());
Attempts:
2 left
💡 Hint
Mockito uses verify() to check method calls on mocks.
🔧 Debug
advanced
2:00remaining
Debugging a test with doThrow on a void method
Given the following test, what error will be thrown when mockService.performAction() is called?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class Service {
    void performAction() {}
}

public class ServiceTest {
    @Test
    void testException() {
        Service mockService = mock(Service.class);
        doThrow(new RuntimeException("Error occurred")).when(mockService).performAction();
        mockService.performAction();
    }
}
ANullPointerException
BRuntimeException with message "Error occurred"
CMockitoException
DNo exception, method does nothing
Attempts:
2 left
💡 Hint
doThrow() makes the mocked void method throw an exception when called.
🧠 Conceptual
advanced
2:00remaining
Why use doAnswer() with void methods in Mockito?
Why would a tester use doAnswer() when mocking a void method instead of doNothing() or doThrow()?
ATo execute custom code or logic when the void method is called
BTo automatically call the real method implementation
CTo ignore the method call silently without any effect
DTo verify the method was never called
Attempts:
2 left
💡 Hint
doAnswer() lets you define what happens when the method is called.
❓ framework
expert
3:00remaining
Correct Mockito syntax to mock a void method throwing checked exception
Which option correctly mocks a void method performAction() to throw a checked exception IOException when called, using Mockito in JUnit?
JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import java.io.IOException;

class Service {
    void performAction() throws IOException {}
}

public class ServiceTest {
    @Test
    void testCheckedException() throws IOException {
        Service mockService = mock(Service.class);
        // Which option correctly mocks performAction() to throw IOException?
    }
}
AdoThrow(new IOException("IO error")).when(mockService).performAction();
Bwhen(mockService.performAction()).thenThrow(new IOException("IO error"));
CdoThrow(IOException.class).when(mockService).performAction();
Dwhen(mockService.performAction()).thenReturn(new IOException("IO error"));
Attempts:
2 left
💡 Hint
Use doThrow() for void methods throwing checked exceptions.

Practice

(1/5)
1. What is the main purpose of mocking void methods in JUnit tests?
easy
A. To convert void methods into methods that return values
B. To control their behavior and verify interactions without executing actual code
C. To automatically generate return values for void methods
D. To disable all tests that call void methods

Solution

  1. Step 1: Understand void methods in tests

    Void methods do not return values, so mocking helps control their side effects during tests.
  2. Step 2: Purpose of mocking void methods

    Mocking allows skipping actual execution and verifying if the method was called, without running real code.
  3. Final Answer:

    To control their behavior and verify interactions without executing actual code -> Option B
  4. Quick Check:

    Mock void methods = control behavior + verify calls [OK]
Hint: Mock void methods to control calls without running code [OK]
Common Mistakes:
  • Thinking void methods return values
  • Assuming mocking changes method return type
  • Believing mocking disables all tests
2. Which Mockito syntax correctly mocks a void method sendEmail() to do nothing when called?
easy
A. doNothing().when(mock).sendEmail();
B. verify(mock).doNothing().sendEmail();
C. mock.sendEmail().doNothing();
D. when(mock.sendEmail()).thenReturn(null);

Solution

  1. Step 1: Recall Mockito syntax for void methods

    Mockito uses doNothing().when(mock).method() to mock void methods doing nothing.
  2. Step 2: Analyze options

    doNothing().when(mock).sendEmail(); matches correct syntax; others misuse when() or verify().
  3. Final Answer:

    doNothing().when(mock).sendEmail(); -> Option A
  4. Quick Check:

    Mock void method to do nothing = doNothing().when() [OK]
Hint: Use doNothing().when(mock).voidMethod() to mock void methods [OK]
Common Mistakes:
  • Using when() with void methods incorrectly
  • Trying to chain doNothing() after method call
  • Confusing verify() with mocking syntax
3. Given the code snippet:
doThrow(new RuntimeException()).when(mock).deleteFile();
mock.deleteFile();

What happens when mock.deleteFile() is called?
medium
A. The test fails to compile
B. The method executes normally without exception
C. The method returns null
D. A RuntimeException is thrown

Solution

  1. Step 1: Understand doThrow() usage

    doThrow() tells Mockito to throw the specified exception when the void method is called.
  2. Step 2: Analyze method call effect

    Calling mock.deleteFile() triggers the RuntimeException as mocked.
  3. Final Answer:

    A RuntimeException is thrown -> Option D
  4. Quick Check:

    doThrow() causes exception on void method call [OK]
Hint: doThrow() makes void method throw exception when called [OK]
Common Mistakes:
  • Expecting method to run normally
  • Thinking void methods return null
  • Confusing doThrow() with doNothing()
4. Identify the error in this Mockito code snippet:
doNothing().when(mock.deleteFile());
medium
A. Incorrect use of when() with method call inside
B. Missing exception type in doNothing()
C. doNothing() cannot be used with void methods
D. No error, code is correct

Solution

  1. Step 1: Check Mockito syntax for mocking void methods

    Correct syntax is doNothing().when(mock).method(), not passing method call inside when().
  2. Step 2: Identify error in code

    Code incorrectly calls method inside when(), causing syntax error.
  3. Final Answer:

    Incorrect use of when() with method call inside -> Option A
  4. Quick Check:

    when() expects mock object, not method call [OK]
Hint: Use when(mock).method(), not when(method()) [OK]
Common Mistakes:
  • Calling method inside when() instead of after when(mock)
  • Thinking doNothing() needs exception type
  • Believing doNothing() can't mock void methods
5. You want to verify that a void method logAction() was called exactly twice during a test. Which Mockito code correctly does this?
hard
A. verify(mock).logAction(times(2));
B. doNothing().when(mock).logAction(); verify(mock).logAction();
C. verify(mock, times(2)).logAction();
D. when(mock.logAction()).thenReturn(2);

Solution

  1. Step 1: Recall Mockito verify syntax for call count

    Use verify(mock, times(n)).method() to check method called n times.
  2. Step 2: Analyze options

    verify(mock, times(2)).logAction(); uses correct syntax; others misuse verify or when with void methods.
  3. Final Answer:

    verify(mock, times(2)).logAction(); -> Option C
  4. Quick Check:

    Verify call count = verify(mock, times(n)) [OK]
Hint: Use verify(mock, times(n)) to check void method call count [OK]
Common Mistakes:
  • Using when() with void methods to check calls
  • Misplacing times() inside method call
  • Not specifying times() for multiple calls
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard