Created
February 2, 2016 16:52
-
-
Save arttuladhar/89ab272275a51b42777e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.art.test; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.io.OutputStreamWriter; | |
import java.util.Iterator; | |
import org.junit.Test; | |
import org.mockito.Mockito; | |
import static org.junit.Assert.*; | |
import static org.mockito.Mockito.*; | |
public class MockitoTest{ | |
@Test | |
public void testIterator(){ | |
//Mock Class | |
Iterator i = mock(Iterator.class); | |
//Arrange (Stub) | |
Mockito.when(i.next()).thenReturn("Hello").thenReturn("World"); | |
String result = i.next() + " " + i.next(); | |
assertEquals("Hello World", result); | |
} | |
@Test | |
public void testWithArgs(){ | |
//Mock Class | |
Comparable c = mock(Comparable.class); | |
//Stubing a Mocked Class [when..thenReturn] | |
when (c.compareTo("Test")).thenReturn(1); | |
assertEquals(1, c.compareTo("Test")); | |
} | |
//Using Matchers [Preffered] | |
@Test | |
public void testWithoutArgs(){ | |
//Mock Class | |
Comparable c = Mockito.mock(Comparable.class); | |
//Using Matchers | |
when(c.compareTo(anyInt())).thenReturn(-1); | |
assertEquals(-1, c.compareTo(5)); | |
} | |
//Using Mockito.doReturn [Optional] | |
@Test | |
public void testWithoutArgsNew(){ | |
//Mock Class | |
Comparable c = mock(Comparable.class); | |
//Using doReturn | |
doReturn(-1).when(c).compareTo(anyInt()); | |
assertEquals(-1, c.compareTo(5)); | |
} | |
/* | |
* Verifying (OutputStreamWriter) osw rethrows when mock (OutputStream) | |
* throws an exception | |
*/ | |
@Test(expected=IOException.class) | |
public void testRethrow() throws IOException{ | |
OutputStream mock = mock(OutputStream.class); | |
OutputStreamWriter osw = new OutputStreamWriter(mock); | |
doThrow(new IOException()).when(mock).close(); | |
osw.close(); | |
} | |
/* | |
* Verifying OutputStreamWriter propagates close method call to OutputStream Mock | |
* Object. | |
*/ | |
@Test | |
public void testOnClose() throws IOException{ | |
OutputStream mock = mock(OutputStream.class); | |
OutputStreamWriter osw = new OutputStreamWriter(mock); | |
osw.close(); | |
verify(mock).close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment