0
0
JUnittesting~5 mins

Spy objects in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a Spy object in testing?
A Spy object is a special test double that wraps a real object to record how it is used, allowing verification of method calls while still executing the original methods.
Click to reveal answer
intermediate
How does a Spy differ from a Mock?
A Spy calls the real methods and records interactions, while a Mock replaces the real object and only simulates behavior without calling real methods.
Click to reveal answer
beginner
Show a simple example of creating a Spy in JUnit with Mockito.
Example:<br>
List<String> list = new ArrayList<>();
List<String> spyList = Mockito.spy(list);
spyList.add("test");
Mockito.verify(spyList).add("test");
Click to reveal answer
intermediate
Why use a Spy object instead of a real object in tests?
Using a Spy lets you check how the object is used (like which methods were called) without losing the real behavior, helping to verify interactions and side effects.
Click to reveal answer
advanced
What is a common pitfall when using Spy objects?
A common pitfall is that Spies call real methods, which can cause unwanted side effects or errors if the real methods depend on external systems or state.
Click to reveal answer
What does a Spy object do in a test?
ACalls real methods and records interactions
BOnly simulates methods without calling real ones
CReplaces the entire system under test
DGenerates random test data
Which library is commonly used with JUnit to create Spy objects?
AMockito
BJUnitParams
CAssertJ
DHamcrest
What is a risk when using Spy objects in tests?
ASpy objects never call real methods
BReal methods may cause side effects
CSpy objects cannot verify method calls
DSpy objects replace the entire application
How do you verify a method call on a Spy object in Mockito?
AverifyMethod(spyObject, methodName)
BspyObject.assertCalled()
CMockito.verify(spyObject).methodName()
DspyObject.checkCall()
Which statement is true about Spy objects?
AThey do not record method calls
BThey completely replace real objects with fake ones
CThey cannot be used with JUnit
DThey wrap real objects and allow partial mocking
Explain what a Spy object is and when you would use it in testing.
Think about how a Spy lets you check real method calls.
You got /3 concepts.
    Describe how to create and verify a Spy object in a JUnit test using Mockito.
    Remember the example with a List and verify method call.
    You got /3 concepts.