← Back to Advanced Java Course | Chapter 9: Testing | Lesson 1 of 1

Java में Mockito

Mockito आपके program के हिस्सों के लिए नकली stand-ins बनाता है ताकि आप एक टुकड़े को अकेले test कर सकें, जैसे किसी व्यक्ति की जगह crash dummy उपयोग करना। आप यह भी जांच सकते हैं कि उनका सही तरीके से उपयोग हुआ।
Syntax
java
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

java
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());
	}
}

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

java
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());
	}
}

Mocking Void Methods

Void methods assert करने के लिए कोई value return नहीं करते, लेकिन Mockito फिर भी आपको इन्हें stub करने देता है -- call होने पर एक exception फेंकने के लिए, या doAnswer() के ज़रिए एक custom callback trigger करने के लिए -- और, सबसे ज़रूरी, बाद में यह verify करने के लिए कि वे असल में बिल्कुल invoke हुए।

उदाहरण: Mocking Void Methods

java
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
	}
}

Verifying Method Interactions

return values stub करने के अलावा, Mockito आपको verify() का उपयोग करके यह verify करने देता है कि कोई method असल में call हुआ और कितनी बार। अगर expected interaction कभी नहीं हुआ तो यह test को fail कर देता है, जो 'क्या वाकई एक notification भेजा गया' जैसे side effects जांचने के लिए ज़रूरी है जो किसी return value में नहीं दिखते।

उदाहरण: Verifying Method Interactions

java
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
	}
}

Argument Matchers

any() और eq() जैसे argument matchers आपको पास किए गए exact argument value को तय किए बिना किसी method call को stub या verify करने देते हैं। ये खासतौर पर तब उपयोगी हैं जब असली argument test-write समय पर कुछ dynamic और अप्रत्याशित हो, जैसे एक generated ID या current timestamp।

उदाहरण: Argument Matchers

java
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));
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. matchers और plain values को एक call में मिलाना, जैसे when(mock.find(any(), "x")), जो InvalidUseOfMatchersException फेंकता है; plain value के लिए eq("x") का उपयोग करें।
  2. when(spy.method()) से एक spy को stub करना, जो असल में पहले असली method को call कर देता है; doReturn(value).when(spy).method() का उपयोग करें।
  3. यह भूल जाना कि verify(mock).method() default रूप से बिल्कुल एक call का मतलब रखता है, इसलिए दो बार call होने वाला method times(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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.