mardi 26 mai 2015

What is stubbing of methods, When should we stub methods and How to decide which methods are to be stubbed

I am writing JUNIT test cases for my project.We are using Mockito and PowerMock. Firstly i wanted to understand the difference between Mock and Stub.After going through few links and articles i could understand(not a very clear picture) a bit of mock object but nothing about stub. Following are my questions

1. What is a Mock object and when should we create a mock object ?

2. What is a Stub ?

3. What is stubbing of methods ?

4. When should we stub methods ?

5. How do we decide which methods are to be and can be stubbed

Here is my understanding of Mock Object.Say we have a class A

public class A{
}  

A a = Mockito.Mock(A.class);

It creates a dummy(Proxy) object of class A and all the instance variables of this class are not initialized and the mock object contains the methods of class A. Is my understanding correct ?

For Class A when we can create an object this way

A a = new A();

Why should and When should we say Mockito.mock(A.class);

The other thing as per my understanding is as we cannot create an object for an interface, we can use mockito to create a mock object for that interface.

For Ex : we have

public interface ShipNoticeService{

void test();
} 

For the above interface we can say

Mockito.mock(ShipNoticeService.class).

And for stubbing of methods i have gone through this link

http://ift.tt/1Aryzok

And following is the example given for stubbing

//stubbing

when(mockedList.get(0)).thenReturn("first");

when(mockedList.get(1)).thenThrow(new RuntimeException());

Say I have class like this with the following line

public class ShipNoticeAddin extends BaseDocumentAddin {

private DocumentManager documentManager= ServiceLocatorBeanFactory.getService(DocumentManager.class);

}

And in my test case for the above class if i say

DocumentManager documentManager= Mockito.mock(DocumentManager.class);
PowerMockito.mockStatic(ServiceLocatorBeanFactory.class);
PowerMockito.when(ServiceLocatorBeanFactory.getService(DocumentManager .class)).thenReturn(documentManager);

Does the above code mean stubbing ?

Also can the points 2 to 5 be explained in layman terms. The one i am not able to understand clearly is the Stub . Can the Stub be explained more clearly and in layman terms .

Aucun commentaire:

Enregistrer un commentaire