एक उदाहरण मैं एक सेवा वर्ग है कि परीक्षण विधि से बुलाया जाएगा है के लिए:
public interface AService{
public ReturnObject addNewItem(String param1, String param2);
public ReturnObject addNewItem(String param1, String param2, boolean isOk);
}
MainServiceImpl कक्षा में एक विधि होगा नीचे एक अधिभारित विधि को कॉल करें:
@Service("mainService")
public class MainServiceImpl implements MainService {
@Autowired
private AService aService;
public ReturnObject saveItem(String itemName, String itemCode){
return aService.addNewItem(itemName, itemCode);
}
}
तो जब हमें saveItem
के लिए यूनिट टेस्ट लिखना है, तो addNewItem
के रूप में पहले से अधिभारित विधि को कॉल करने के लिए विधि, यदि आपने नकली बनाने के सामान्य तरीके का उपयोग किया था तो आप उत्तर ऑब्जेक्ट रिटर्न में जो चाहते हैं उसे वापस नहीं करेंगे।
@RunWith(PowerMockRunner.class)
@PrepareForTest({ })
public class ItemTest{
@Test
public void testSaveItem() throws Exception {
//create a real object of MainServiceImpl
MainServiceImpl mainService = new MainServiceImpl();
//create a normal way for a mocking object
AService aService = Mockito.mock(AService.class);
// Add mock object to MainServiceImpl instance
ReflectionTestUtils.setField(mainService, "aService", aService);
//Mock when aService call to addNewItem() method
PowerMockito.when(aService , "addNewItem", Mockito.anyString(), Mockito.anyString()).then(new Answer<ReturnObject>() {
@Override
public ReturnObject answer(InvocationOnMock invocation) throws Throwable {
return new ReturnObject("saveOK");
}
});
ReturnObject returnObj = mainService.saveItem("Book", "Code123");
Assert.assertNotNull(returnObj);
}
}
कोशिश testSaveItem तो सफलता नीचे testSaveItem साथ द्वारा उपरोक्त को बदलने के लिए:
@Test
public void testSaveItem() throws Exception {
//create a real object of MainServiceImpl
MainServiceImpl mainService = new MainServiceImpl();
//create a special way for a mocking object by add
//the answer at create the mock object
final Answer<ReturnObject> answer = new Answer<ReturnObject>() {
@Override
public ReturnObjectanswer(final InvocationOnMock invocation) throws Throwable {
return new ReturnObject("saveOK");
}
};
AService aService = Mockito.mock(AService.class, answer);
// Add mock object to MainServiceImpl instance
ReflectionTestUtils.setField(mainService, "aService", aService);
//Mock when aService call to addNewItem() method
PowerMockito.when(aService , "addNewItem", Mockito.anyString(), Mockito.anyString()).then(new Answer<ReturnObject>() {
@Override
public ReturnObject answer(InvocationOnMock invocation) throws Throwable {
return new ReturnObject("saveOK");
}
});
ReturnObject returnObj = mainService.saveItem("Book", "Code123");
Assert.assertNotNull(returnObj);
}
इसी http://stackoverflow.com/questions/5594645/verify-whether-one-of-three-methods को -इस-इनकॉक्ड-साथ-मॉकिटो – BretC
तो मैं समझता हूं कि मैं एक मॉकबिल्डर विधि में दोनों मोजे नहीं प्राप्त कर सकता हूं? – Chry007
नहीं, मुझे पता नहीं है कि मुझे पता है – BretC