📜 ⬆️ ⬇️

Six simple examples on Mockito (translation)

Small comment:
/ *
I decided to familiarize myself with what this library is of, 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 it usually happens. ;)
* /

Mockito is a great mock library for Java. I am fascinated by how easy it is to use in comparison with other similar libraries from the world of Java and .NET. In this article, I give everything that you need to start in six very easy examples.

To get started, download the mockito from http://mockito.org/ (at the time of writing, it leads to https://code.google.com/p/mockito/ ).
Or just add it depending on the pom of the maven project:
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency> <!--      1.10.10 --> 

Almost all the fun 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 returns, then subsequent calls will return only the last value (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 “causes” 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 assertions.
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 some arguments, but you don’t care what is passed to them or predict it is impossible, 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 problem because 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 the 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(); } 

In this example, an IOException is thrown when the close method is called on the OutputStream stub. We easily verify that OutputStreamWriter sends such an event to the outside.
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 check that OutputStreamWriter makes a call to the close () method in a 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 gamers. Use the eq (value) matcher to convert a literal into a matcher that compares the value. Mockito provides a lot of ready-made matchers, 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 don’t know how long the buffer is going to pass to us. Here we cannot use comparison for equality. However, we can file our own match:
  @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<byte[]> arrayStartingWithA = new BaseMatcher<byte[]>() { @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. And now take and refill all this isokraschyna 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<byte[]> arrayStartingWithA = new BaseMatcher<byte[]>() { @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/

')

Source: https://habr.com/ru/post/243155/


All Articles