
Six Simple Mockito Examples (Translation)
- Tutorial
Little comment:
/ *
I decided to get acquainted with what this library is all about, and found a wonderful article , the reading of which I would like to consolidate, for which I decided to translate it into Russian.
Of course, constructive criticism is accepted.
I hope that the comments will be more useful than the article itself, as is usually the case. ;)
* /
I decided to get acquainted with what this library is all about, and found a wonderful article , the reading of which I would like to consolidate, for which I decided to translate it into Russian.
Of course, constructive criticism is accepted.
I hope that the comments will be more useful than the article itself, as is usually the case. ;)
* /
Mockito is a great Java mock library. I am fascinated by how easy it is to use in comparison with other similar libraries from the Java and .NET world. In this article, I give everything you need to get started in six very easy examples.
To get started, download mockito from http://mockito.org/ (at the time of writing it leads to https://code.google.com/p/mockito/ ).
Or just add this depending on the pom maven project:
org.mockito mockito-core RELEASE test
Almost all of the most interesting can be taken from the org.mockito.Mockito class (or you can statically import its methods, which I use in this article). So, let's begin.
To create a stub (or mock), use mock (class) . Then use when (mock) .thenReturn (value) to specify the return value for the method. If you specify more than one return value, they will be returned by the method sequentially until the last one is returned, after that only subsequent value will be returned in subsequent calls (so that the method always returns the same value, just specify it once). For example:
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Test;
....
@Test
public void iterator_will_return_hello_world() {
//подготавливаем
Iterator i = mock(Iterator.class);
when(i.next()).thenReturn("Hello").thenReturn("World");
//выполняем
String result = i.next()+" "+i.next();
//сравниваем
assertEquals("Hello World", result);
}
This example demonstrates the creation of a mock iterator and “forces” it to return “Hello” the first time the next () method is called . Subsequent calls to this method will return "World." After that, we can perform the usual assertes.
Stubs can also return different values depending on the arguments passed to the method. Example:
@Test
public void with_arguments() {
Comparable c = mock(Comparable.class);
when(c.compareTo("Test")).thenReturn(1);
assertEquals(1, c.compareTo("Test"));
}
Here we create a Comparable stub object and return 1 if it is compared with a specific String value (“Test”, in this case).
If the method has any arguments, but you don’t care what will be passed to them or it is impossible to predict, then use anyInt () (and alternative values for other types). Example:
@Test
public void with_unspecified_arguments() {
Comparable c = mock(Comparable.class);
when(c.compareTo(anyInt())).thenReturn(-1);
assertEquals(-1, c.compareTo(5));
}
This stub returns -1 regardless of the argument passed. Void methods are a bit of a problem since you cannot use them in the when () method .
An alternative syntax in this situation would be doReturn (result) .when (mock_object) .void_method_call (); . Instead of returning a result, you can also use .thenThrow () or doThrow () for void methods. Example:
@Test(expected=IOException.class)
public void OutputStreamWriter_rethrows_an_exception_from_OutputStream()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
doThrow(new IOException()).when(mock).close();
osw.close();
}
This example throws an IOException when the close method is called on the OutputStream stub. We can easily verify that OutputStreamWriter throws such an exit out.
To verify that the method was actually called (typical use of stub objects), we can use verify (mock_object) .method_call; . Example:
@Test
public void OutputStreamWriter_Closes_OutputStream_on_Close()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
osw.close();
verify(mock).close();
}
In this example, we verify that OutputStreamWriter makes a call to the close () method in the nested OutputStream.
You can use arguments in methods and substitutions for them, such as anyInt () , as in one of the previous examples. It is worth noting that you cannot mix literals and matchers. Use the eq (value) matcherto convert a literal to a matcher that compares the value. Mockito provides a ton of ready-made matchmakers, but sometimes you may need a more flexible approach. For example, OutputStreamWriter will buffer the output and then pass it to the wrapped object when the buffer is full, but we do not know how long the buffer is going to be passed to us. Here we cannot use equality comparison. However, we can file our own matcher:
@Test
public void OutputStreamWriter_Buffers_And_Forwards_To_OutputStream()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
osw.write('a');
osw.flush();
// не можем делать так, потому что мы не знаем,
// насколько длинным может быть массив
// verify(mock).write(new byte[]{'a'}, 0, 1);
BaseMatcher arrayStartingWithA = new BaseMatcher() {
@Override
public void describeTo(Description description) {
// пустота
}
// Проверяем, что первый символ - это A
@Override
public boolean matches(Object item) {
byte[] actual = (byte[]) item;
return actual[0] == 'a';
}
};
// проверяем, что первый символ массива - это A, и что другие два аргумента равны 0 и 1.
verify(mock).write(argThat(arrayStartingWithA), eq(0), eq(1));
}
And that’s all you need to get started. Now take and refactor this whole izimokschina in your projects!
All class text with tests:
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Iterator;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.Test;
public class MockitoTests {
@Test
public void iterator_will_return_hello_world() {
//подготавливаем
Iterator i = mock(Iterator.class);
when(i.next()).thenReturn("Hello").thenReturn("World");
//выполняем
String result = i.next() + " " + i.next();
//сравниваем
assertEquals("Hello World", result);
}
@Test
public void with_arguments() {
Comparable c = mock(Comparable.class);
when(c.compareTo("Test")).thenReturn(1);
assertEquals(1, c.compareTo("Test"));
}
@Test
public void with_unspecified_arguments() {
Comparable c = mock(Comparable.class);
when(c.compareTo(anyInt())).thenReturn(-1);
assertEquals(-1, c.compareTo(5));
}
@Test(expected = IOException.class)
public void OutputStreamWriter_rethrows_an_exception_from_OutputStream()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
doThrow(new IOException()).when(mock).close();
osw.close();
}
@Test
public void OutputStreamWriter_Closes_OutputStream_on_Close()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
osw.close();
verify(mock).close();
}
@Test
public void OutputStreamWriter_Buffers_And_Forwards_To_OutputStream()
throws IOException {
OutputStream mock = mock(OutputStream.class);
OutputStreamWriter osw = new OutputStreamWriter(mock);
osw.write('a');
osw.flush();
// не можем делать так, потому что мы не знаем,
// насколько длинным может быть массив
// verify(mock).write(new byte[]{'a'},0,1);
BaseMatcher arrayStartingWithA = new BaseMatcher() {
@Override
public void describeTo(Description description) {
// пустота
}
// Проверяем, что первый символ - это A
@Override
public boolean matches(Object item) {
byte[] actual = (byte[]) item;
return actual[0] == 'a';
}
};
// проверяем, что первый символ массива - это A, и что другие два аргумента равны 0 и 1.
verify(mock).write(argThat(arrayStartingWithA), eq(0), eq(1));
}
}
PS: Then you can read the introduction to PowerMock: http://habrahabr.ru/post/172239/ .
And this article: http://habrahabr.ru/post/72617/