Thursday, April 11, 2013

org.mockito

Sometimes we need Stub or Mock objects as following:

import org.mockito.Mock;
import org.mockito.Mockito;

    @Mock
    private EntityManager em;
(...)

        @SuppressWarnings("rawtypes")
        public Object find(Class class1, Object obj) {
            Object object = Mockito.mock(Object.class);
            return object;
        }

Let me look at definitions from DZone Refcardz (by M.Zajaczkowski) about Mockito:

1. Dummy = an empty object passed in an invocation (usually only
to satisfy a compiler when a method ar- gument is required)

2. Fake = an object having a functional implementation, but usually
in a simplified form, just to satisfy the test (e.g., an in-memory
database)

3. Stub = an object with hardcoded behavior suitable for a given
test (or a group of tests)

4. Mock = an object with the ability to a) have a programmed
expected behavior, and b) verify the interactions occurring in its
lifetime (this object is usually created with the help of mocking
framework)

5. Spy = a mock created as a proxy to an existing real object; some
methods can be stubbed, while the un- stubbed ones are forwarded
to the covered object

We can create a mock iterator or mock list, for example in such way:

import static org.mockito.Mockito.*;
import java.util.Iterator;
import org.junit.Test;
(...)
    @Test
    public void mockito_example_test01(){
        Iterator iter = mock(Iterator.class);
         List mockedList = mock(List.class);
         mockedList.add("one");


Another example is related with return value. Stubs can also return different values depending on arguments passed into the method, for example...

    @Test
    public void with_return_value(){
        Comparable c = mock(Comparable.class);
        when(c.compareTo("Test")).thenReturn(1);
        assertEquals(1,c.compareTo("Test"));
    }

No comments: