Bird
Raised Fist0
JUnittesting~10 mins

Answer interface for dynamic responses in JUnit - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a JUnit test method that asserts two strings are equal.

JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.[1];

public class SampleTest {
    @Test
    void testStrings() {
        String expected = "hello";
        String actual = "hello";
        [1](expected, actual);
    }
}
Drag options to blanks, or click blank then click option'
AassertNull
BassertFalse
CassertTrue
DassertEquals
Attempts:
3 left
💡 Hint
Common Mistakes
Using assertTrue instead of assertEquals causes the test to check a boolean, not equality.
Using assertNull or assertFalse does not compare two strings.
2fill in blank
medium

Complete the code to create a dynamic test name using JUnit 5's @DisplayName annotation.

JUnit
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.DisplayName;

public class DynamicNameTest {
    @Test
    @DisplayName("Test for user: [1]")
    void testUser() {
        // test code here
    }
}
Drag options to blanks, or click blank then click option'
A"John"
BJohn
CuserName
D"userName"
Attempts:
3 left
💡 Hint
Common Mistakes
Not using quotes causes a compilation error.
Using a variable name without quotes does not work in @DisplayName.
3fill in blank
hard

Fix the error in the code to correctly implement a dynamic test with JUnit 5's @TestFactory.

JUnit
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class DynamicTests {
    @TestFactory
    Stream<DynamicTest> dynamicTests() {
        return Stream.of(
            DynamicTest.dynamicTest("Test 1", () -> [1])
        );
    }
}
Drag options to blanks, or click blank then click option'
AassertTrue(1 > 2)
BassertEquals(2, 1 + 2)
CassertEquals(2, 1 + 1)
DassertNull(null)
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong expected values causes test failure.
Using assertions that do not compile or are invalid in lambda.
4fill in blank
hard

Fill both blanks to create a parameterized test method that uses @ValueSource with integers.

JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.[1];

public class ParamTest {
    @ParameterizedTest
    @[2](ints = {1, 2, 3})
    void testNumbers(int number) {
        // test code
    }
}
Drag options to blanks, or click blank then click option'
AValueSource
BCsvSource
DMethodSource
Attempts:
3 left
💡 Hint
Common Mistakes
Using @CsvSource or @MethodSource without proper format causes errors.
Mismatching import and annotation names.
5fill in blank
hard

Fill all three blanks to create a dynamic test stream that tests if strings are not empty.

JUnit
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class StringTests {
    @TestFactory
    Stream<DynamicTest> dynamicTestsForStrings() {
        String[] inputs = {"apple", "", "banana"};
        return Stream.of(inputs).map(input ->
            DynamicTest.dynamicTest("Test: " + input, () -> {
                [1].assertTrue(!input.[2](), "String is empty");
            })
        );
    }
}
Drag options to blanks, or click blank then click option'
Aorg.junit.jupiter.api.Assertions
BisEmpty
CassertTrue
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Calling assertTrue without the Assertions class causes errors.
Using length() instead of isEmpty() changes the logic.
Mixing up assertTrue and assertFalse.

Practice

(1/5)
1. What is the main purpose of the Answer interface in JUnit mocking frameworks like Mockito?
easy
A. To verify the number of method calls on a mock
B. To create static return values for mocked methods
C. To provide dynamic responses based on method input during mocking
D. To reset mocks to their original state

Solution

  1. Step 1: Understand the role of Answer interface

    The Answer interface allows you to define custom behavior for mocked methods dynamically, based on the input arguments.
  2. Step 2: Compare with other mocking features

    Static return values are simpler but less flexible. Verification and reset are different features unrelated to Answer.
  3. Final Answer:

    To provide dynamic responses based on method input during mocking -> Option C
  4. Quick Check:

    Answer interface = dynamic mock responses [OK]
Hint: Answer interface means dynamic mock responses based on input [OK]
Common Mistakes:
  • Confusing Answer with static return values
  • Mixing Answer with verification methods
  • Thinking Answer resets mocks
2. Which of the following is the correct syntax to implement the Answer interface in Mockito for a method that returns the length of a String argument?
easy
A. when(mock.method(anyString())).thenAnswer(invocation -> ((String)invocation.getArgument(0)).length());
B. when(mock.method(anyString())).thenAnswer(invocation -> invocation.length());
C. when(mock.method(anyString())).thenReturn(invocation.getArgument(0).length());
D. when(mock.method(anyString())).thenAnswer(invocation -> invocation.getArgument(1).length());

Solution

  1. Step 1: Identify correct use of thenAnswer with lambda

    thenAnswer expects a lambda with InvocationOnMock parameter; ((String)getArgument(0)) fetches first argument.
  2. Step 2: Check argument index and method calls

    Using ((String)getArgument(0)).length() correctly gets length of first String argument. The option using invocation.length() misses getArgument, the option using thenReturn is incorrect because invocation is unavailable, the option using getArgument(1) uses wrong argument index.
  3. Final Answer:

    when(mock.method(anyString())).thenAnswer(invocation -> ((String)invocation.getArgument(0)).length()); -> Option A
  4. Quick Check:

    thenAnswer + ((String)getArgument(0)) = correct syntax [OK]
Hint: Use ((String)getArgument(0)) inside thenAnswer lambda for first param [OK]
Common Mistakes:
  • Using thenReturn instead of thenAnswer for dynamic response
  • Accessing wrong argument index
  • Calling length() on invocation instead of argument
3. Given the following Mockito stub using Answer interface:
when(mock.calculate(anyInt())).thenAnswer(invocation -> {
  int x = (int) invocation.getArgument(0);
  return x * 2;
});
System.out.println(mock.calculate(5));

What will be printed?
medium
A. 5
B. Throws NullPointerException
C. 0
D. 10

Solution

  1. Step 1: Analyze the Answer implementation

    The Answer lambda takes the first argument (5), multiplies it by 2, and returns the result.
  2. Step 2: Calculate the output of mock.calculate(5)

    5 * 2 = 10, so the printed output is 10.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    5 * 2 = 10 [OK]
Hint: Multiply input by 2 inside thenAnswer returns 10 for input 5 [OK]
Common Mistakes:
  • Assuming static return value 5
  • Confusing argument index
  • Expecting exception without cause
4. Consider this Mockito stub using Answer interface:
when(mock.concat(anyString(), anyString())).thenAnswer(invocation -> {
  String a = invocation.getArgument(0);
  String b = invocation.getArgument(1);
  return a + b;
});

Which of the following is a bug in this code?
medium
A. Missing cast to String for getArgument
B. Using getArgument with wrong index
C. Using thenAnswer instead of thenReturn
D. No bug, code works correctly

Solution

  1. Step 1: Check getArgument usage

    getArgument returns Object by default; it must be cast to String to avoid ClassCastException.
  2. Step 2: Identify missing cast

    Code assigns getArgument(0) and getArgument(1) directly to String variables without casting, which is incorrect.
  3. Final Answer:

    Missing cast to String for getArgument -> Option A
  4. Quick Check:

    getArgument needs cast to String [OK]
Hint: Always cast getArgument to expected type [OK]
Common Mistakes:
  • Ignoring required casting of getArgument
  • Thinking thenAnswer is wrong here
  • Assuming getArgument returns typed value
5. You want to mock a method process(int a, int b) so that it returns the sum of the two arguments only if both are positive; otherwise, it returns zero. Which is the best way to implement this using the Answer interface in Mockito?
hard
A. Use thenReturn(0) for all calls and verify arguments separately
B. Use thenAnswer with a lambda that checks both arguments and returns sum or zero accordingly
C. Use thenAnswer with a lambda that always returns the first argument
D. Use thenThrow to throw exception if arguments are negative

Solution

  1. Step 1: Understand requirement for conditional return

    The method must return sum if both inputs are positive, else zero, which requires dynamic logic.
  2. Step 2: Choose correct Answer implementation

    Using thenAnswer with a lambda that checks both arguments and returns sum or zero fits perfectly. Other options either ignore conditions or throw exceptions unnecessarily.
  3. Final Answer:

    Use thenAnswer with a lambda that checks both arguments and returns sum or zero accordingly -> Option B
  4. Quick Check:

    Conditional logic in thenAnswer = Use thenAnswer with a lambda that checks both arguments and returns sum or zero accordingly [OK]
Hint: Use thenAnswer with conditional logic for dynamic return [OK]
Common Mistakes:
  • Using thenReturn for conditional logic
  • Ignoring argument checks
  • Throwing exceptions instead of returning zero
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