Challenge - 5 Problems
Stub Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a simple stub method call
What will be the output of this JUnit test using a stub object?
JUnit
public interface Calculator {
int add(int a, int b);
}
public class CalculatorStub implements Calculator {
@Override
public int add(int a, int b) {
return 42; // stub always returns 42
}
}
@Test
public void testAdd() {
Calculator calc = new CalculatorStub();
int result = calc.add(5, 3);
System.out.println(result);
}Attempts:
2 left
💡 Hint
Remember, a stub returns fixed values regardless of input.
✗ Incorrect
The stub method add always returns 42, ignoring the input values. So the printed output is 42.
❓ assertion
intermediate2:00remaining
Correct assertion for stubbed method
Which assertion correctly verifies the stubbed method returns the expected value?
JUnit
public interface Service {
String getData();
}
public class ServiceStub implements Service {
@Override
public String getData() {
return "stubbed data";
}
}
@Test
public void testGetData() {
Service service = new ServiceStub();
String data = service.getData();
// Which assertion is correct here?
}Attempts:
2 left
💡 Hint
Use the proper JUnit assertion to compare string values.
✗ Incorrect
assertEquals compares string content correctly. Using == compares references and may fail.
🔧 Debug
advanced2:00remaining
Identify the stub causing test failure
Given this test and stub, why does the test fail?
JUnit
public interface UserRepository {
boolean exists(String username);
}
public class UserRepositoryStub implements UserRepository {
@Override
public boolean exists(String username) {
return false; // stub always returns false
}
}
@Test
public void testUserExists() {
UserRepository repo = new UserRepositoryStub();
boolean exists = repo.exists("admin");
assertTrue(exists);
}Attempts:
2 left
💡 Hint
Check what the stub method returns and what the assertion expects.
✗ Incorrect
The stub always returns false, but the test expects true, so the assertion fails.
🧠 Conceptual
advanced1:30remaining
Purpose of stub objects in unit testing
What is the main purpose of using stub objects in unit testing?
Attempts:
2 left
💡 Hint
Think about how stubs help focus tests on one part of the code.
✗ Incorrect
Stubs provide fixed responses to isolate the tested unit from dependencies.
❓ framework
expert2:30remaining
Using Mockito to create a stub method
Which Mockito code snippet correctly stubs a method to return "hello" when called?
JUnit
public interface GreetingService {
String greet();
}
@Test
public void testGreet() {
GreetingService mockService = Mockito.mock(GreetingService.class);
// Which line stubs greet() to return "hello"?
}Attempts:
2 left
💡 Hint
Check the correct Mockito syntax for stubbing methods.
✗ Incorrect
Mockito.when(...).thenReturn(...) is the correct syntax to stub a method.