'How to Mock in Integration Tests - Junit
Im doing integration tests and one of my service is using firebase call to save the data. I want to mock the internal method call that uses the firebase call to indirectly mock the firebase.
public class EventFactory {
private static final EnumMap<EventType, EventCommand> command = new EnumMap<>(EventType.class);
public EventFactory(List<EventCommand> cms) {
cms.forEach(c -> command.put(c.getType(), c));
}
public static EventCommand getEvent(EventType eventType) {
EventCommand eventCommand = command.get(eventType);
if (ObjectUtils.isEmpty(eventCommand)) return null;
return eventCommand;
}
}
I have the handler as,
public class AppEventListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handle(Event event) {
EventCommand command = EventFactory.getEvent(event.getEventType());
if (!ObjectUtils.isEmpty(command)) {
command.execute(event);
} else{
log.error("No Command Found For Provided Event");
}
}
}
I have my CommandService as follows,
public class CommandService implements EventCommand{
private final RealTimeDbService realTime;
public CommandService(RealTimeDbService realTime) {
this.realTime = realTime;
}
@Override
public void execute(Event event) {
MyEvent ev = (MyEvent) event;
log.info("Saving To Firebase");
realTime.save(ev.getDocument());
}
}
My RealTimeDbService is as follows,
public class RealTimeDbService {
public void saveDocument(MyDocument myDoc) {
DocumentReference docRef = getCollection("col").document("myKey");
docRef.get().get();
docRef.set(myDoc);
}
public CollectionReference getCollection(String name) {
return FirestoreClient.getFirestore().collection(name);
}
}
Here I want to mock getCollection method to avoid Firebase hit and return some dummy CollectionReference
My Test is as follows
@SpringBootTest(webEnvironment =
SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@Import(TestingConfig.class)
class MyTest{
@Mock private CollectionReference collectionReference;
@Autowired
private AppEventListener appEventListener;
@Spy
private RealTimeDbService realTime;
@Test
void create() {
MyDocument myDoc = createDoc();
Event ev = createEvent()
doReturn(collectionReference).when(realTime).getCollection("col");
appEventListener.handle(ev);
}
}
The problem is the internal method is not mocked, it is getting called and reaching to firebase. How can I avoid it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|