What is the difference between Mockito's when().thenReturn() and @Spy? Mockito के when().thenReturn() और @Spy में क्या अंतर है?
when(mock.method()).thenReturn(value) stubs a method on a full mock object, where every method returns a default value (null, 0, false) unless explicitly stubbed — the mock has no real logic behind it at all.
@Spy wraps a real object instance, so unstubbed methods call through to the actual implementation while specific methods can still be selectively stubbed with doReturn().when(). Spies are useful when you want to test real behavior for most of a class but override just one method (e.g. an external call), though they should be used sparingly since partially-real objects can make tests harder to reason about.
@Mock private PaymentGateway paymentGateway;
when(paymentGateway.charge(100)).thenReturn(true);
@Spy private OrderCalculator calculator = new OrderCalculator();
doReturn(50.0).when(calculator).applyDiscount(anyDouble());when(mock.method()).thenReturn(value) एक पूर्ण मॉक ऑब्जेक्ट पर एक मेथड को स्टब करता है, जहाँ हर मेथड डिफ़ॉल्ट वैल्यू रिटर्न करता है जब तक स्पष्ट रूप से स्टब न किया जाए — मॉक के पीछे कोई वास्तविक लॉजिक नहीं होता।
@Spy एक वास्तविक ऑब्जेक्ट इंस्टेंस को लपेटता है, इसलिए बिना स्टब की गई मेथड्स वास्तविक इम्प्लीमेंटेशन को कॉल करती हैं जबकि विशिष्ट मेथड्स को अभी भी चुनिंदा रूप से स्टब किया जा सकता है। स्पाई उपयोगी होते हैं जब आप किसी क्लास के अधिकांश भाग के लिए वास्तविक व्यवहार टेस्ट करना चाहते हैं।
@Mock private PaymentGateway paymentGateway;
when(paymentGateway.charge(100)).thenReturn(true);
@Spy private OrderCalculator calculator = new OrderCalculator();
doReturn(50.0).when(calculator).applyDiscount(anyDouble());Was this answer clear?