0
0
JUnittesting~10 mins

Why different doubles serve different purposes in JUnit - Test Your Understanding

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

Complete the code to create a simple stub for a dependency.

JUnit
MyService service = new MyService();
Dependency dep = new [1]();
service.setDependency(dep);
Drag options to blanks, or click blank then click option'
AMockDependency
BSpyDependency
CStubDependency
DFakeDependency
Attempts:
3 left
💡 Hint
Common Mistakes
Choosing MockDependency which is used for interaction verification.
2fill in blank
medium

Complete the code to verify that a method was called once using a mock.

JUnit
MockedList list = mock(MockedList.class);
list.add("item");
verify(list, [1]).add("item");
Drag options to blanks, or click blank then click option'
Atimes(1)
BatLeastOnce()
Cnever()
Dtimes(2)
Attempts:
3 left
💡 Hint
Common Mistakes
Using times(2) which expects two calls.
3fill in blank
hard

Fix the error in the spy creation code.

JUnit
List<String> list = new ArrayList<>();
List<String> spyList = [1](list);
spyList.add("test");
Drag options to blanks, or click blank then click option'
Amock
Bfake
Cstub
Dspy
Attempts:
3 left
💡 Hint
Common Mistakes
Using mock() which does not wrap the real object.
4fill in blank
hard

Fill both blanks to create a fake that simulates a database connection and returns a fixed value.

JUnit
class FakeDatabase implements Database {
    public String query(String sql) {
        return [1];
    }
}

Database db = new FakeDatabase();
String result = db.query([2]);
Drag options to blanks, or click blank then click option'
A"fixed result"
B"SELECT * FROM users"
C"dynamic result"
D"DROP TABLE users"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning dynamic result which is not fixed.
Using DROP TABLE which is destructive.
5fill in blank
hard

Fill all three blanks to create a mock, set expectation, and verify interaction.

JUnit
List<String> mockList = [1](List.class);
when(mockList.get([2])).thenReturn("hello");
mockList.get(0);
verify(mockList).get([3]);
Drag options to blanks, or click blank then click option'
Amock
B0
Dspy
Attempts:
3 left
💡 Hint
Common Mistakes
Using spy() instead of mock().
Mismatching indexes in when() and verify().