Java में Mockito
In this page:
ClassName mock = Mockito.mock(ClassName.class);
when(mock.methodName(argument)).thenReturn(value);
verify(mock).methodName(argument);
Creating Mock Objects
Mockito आपकी असली dependencies के लिए नकली, नियंत्रणीय stand-ins बनाता है -- उदाहरण के लिए एक mock database repository या एक mock external API client। यह आपको किसी class की अपनी logic को अलग से test करने देता है बिना अपने test run के दौरान असल में किसी database या network service से टकराए।
उदाहरण: Creating Mock Objects
import static org.mockito.Mockito.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> mockList = mock(List.class); // fake stand-in, no real implementation
when(mockList.size()).thenReturn(10);
System.out.println(mockList.size());
}
}
Login to try C/C++/Java/PHP code in the editor
Spying on Real Objects
Spies किसी असली object को पूरी तरह replace करने के बजाय उसे wrap करते हैं, इसलिए calls default रूप से असली implementation तक पहुंचते हैं। यह आपको यह track करने देता है कि किसी concrete instance पर असल में कौन से methods invoke हुए जबकि selectively सिर्फ उन specific methods को stub करते हुए जिनसे आपको अलग behavior चाहिए।
उदाहरण: Spying on Real Objects
import static org.mockito.Mockito.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> realList = new ArrayList<>();
List<String> spyList = spy(realList); // calls pass through by default
spyList.add("real item");
when(spyList.size()).thenReturn(100); // selectively stubbed
System.out.println(spyList.size());
}
}
Login to try C/C++/Java/PHP code in the editor
Mocking Void Methods
Void methods assert करने के लिए कोई value return नहीं करते, लेकिन Mockito फिर भी आपको इन्हें stub करने देता है -- call होने पर एक exception फेंकने के लिए, या doAnswer() के ज़रिए एक custom callback trigger करने के लिए -- और, सबसे ज़रूरी, बाद में यह verify करने के लिए कि वे असल में बिल्कुल invoke हुए।
उदाहरण: Mocking Void Methods
import static org.mockito.Mockito.*;
public class Main {
interface Logger { void log(String msg); }
public static void main(String[] args) {
Logger mockLogger = mock(Logger.class);
doThrow(new RuntimeException("log failed")).when(mockLogger).log("error");
try {
mockLogger.log("error");
} catch (RuntimeException e) {
System.out.println("Caught: " + e.getMessage());
}
verify(mockLogger).log("error"); // confirms it was actually invoked
}
}
Login to try C/C++/Java/PHP code in the editor
Verifying Method Interactions
return values stub करने के अलावा, Mockito आपको verify() का उपयोग करके यह verify करने देता है कि कोई method असल में call हुआ और कितनी बार। अगर expected interaction कभी नहीं हुआ तो यह test को fail कर देता है, जो 'क्या वाकई एक notification भेजा गया' जैसे side effects जांचने के लिए ज़रूरी है जो किसी return value में नहीं दिखते।
उदाहरण: Verifying Method Interactions
import static org.mockito.Mockito.*;
public class Main {
interface EmailService { void send(String to); }
public static void main(String[] args) {
EmailService mockService = mock(EmailService.class);
mockService.send("[email protected]");
verify(mockService, times(1)).send("[email protected]"); // fails if never called
}
}
Login to try C/C++/Java/PHP code in the editor
Argument Matchers
any() और eq() जैसे argument matchers आपको पास किए गए exact argument value को तय किए बिना किसी method call को stub या verify करने देते हैं। ये खासतौर पर तब उपयोगी हैं जब असली argument test-write समय पर कुछ dynamic और अप्रत्याशित हो, जैसे एक generated ID या current timestamp।
उदाहरण: Argument Matchers
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
public class Main {
interface Repo { String findById(int id); }
public static void main(String[] args) {
Repo mockRepo = mock(Repo.class);
when(mockRepo.findById(anyInt())).thenReturn("found"); // matches any int argument
System.out.println(mockRepo.findById(999));
}
}
Login to try C/C++/Java/PHP code in the editor
- matchers और plain values को एक call में मिलाना, जैसे
when(mock.find(any(), "x")), जोInvalidUseOfMatchersExceptionफेंकता है; plain value के लिएeq("x")का उपयोग करें। when(spy.method())से एक spy को stub करना, जो असल में पहले असली method को call कर देता है;doReturn(value).when(spy).method()का उपयोग करें।- यह भूल जाना कि
verify(mock).method()default रूप से बिल्कुल एक call का मतलब रखता है, इसलिए दो बार call होने वाला methodtimes(2)उपयोग किए बिना fail हो जाता है।
- Mockito का उपयोग testing के लिए mock objects बनाने के लिए किया जाता है।
- Mocks असली dependencies की जगह लेते हैं ताकि एक unit को अलग से test किया जा सके।
- यह tests को केंद्रित और control करने में आसान बनाता है।
Chapter Quiz — Complete all 1 topics to unlock
0/1 topics done
Complete these topics first: