0
0
JUnittesting~5 mins

when().thenReturn() stubbing in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does when().thenReturn() do in JUnit testing?

when().thenReturn() is used to tell a mock object what value to return when a specific method is called. It helps simulate behavior for testing.

Click to reveal answer
beginner
How do you stub a method getName() of a mock object userMock to return "Alice"?
when(userMock.getName()).thenReturn("Alice");
Click to reveal answer
beginner
Why is stubbing useful in unit tests?

Stubbing lets you control the output of dependencies so you can test your code in isolation without relying on real objects or external systems.

Click to reveal answer
intermediate
What happens if you call a method on a mock without stubbing it first?

By default, the mock returns default values like null, 0, or false. It does not execute real code.

Click to reveal answer
intermediate
Can thenReturn() be used to return different values on consecutive calls?

Yes, you can chain thenReturn() calls to return different values each time the method is called.

when(mock.method()).thenReturn(1, 2);
Click to reveal answer
What is the purpose of when().thenReturn() in JUnit?
ATo stub a method call on a mock object
BTo verify a method was called
CTo create a real object
DTo throw an exception
Which of these is a correct stubbing syntax?
AthenReturn(value).when(mock.method());
Bmock.when(method()).thenReturn(value);
Cwhen(mock.method()).thenReturn(value);
Dmock.method().when().thenReturn(value);
If you do not stub a method on a mock, what will it return by default?
AThe real method's return value
BA default value like null or 0
CAn exception
DNothing, it will crash
How can you make a stub return different values on consecutive calls?
AChain multiple <code>thenReturn()</code> calls
BUse multiple <code>when()</code> calls
CUse <code>thenThrow()</code>
DIt is not possible
Which library provides when().thenReturn() for mocking in JUnit tests?
ATestNG
BJUnit
CSelenium
DMockito
Explain how when().thenReturn() helps in unit testing with mocks.
Think about how you tell a mock what to do when a method is called.
You got /4 concepts.
    Describe the default behavior of a mock object when a method is called without stubbing.
    What happens if you forget to stub a method on a mock?
    You got /4 concepts.