Created
June 11, 2013 19:41
-
-
Save dimhold/5759950 to your computer and use it in GitHub Desktop.
Unit tests just for understand: What is a true way of unit testing
This file contains 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 how.to.use.mockito; | |
import static org.hamcrest.CoreMatchers.is; | |
import static org.junit.Assert.assertThat; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.verify; | |
import static org.mockito.Mockito.when; | |
import java.io.ByteArrayInputStream; | |
import java.io.FileOutputStream; | |
import java.io.InputStream; | |
import java.net.URL; | |
import java.nio.channels.FileChannel; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.powermock.api.mockito.PowerMockito; | |
import org.powermock.core.classloader.annotations.PrepareForTest; | |
import org.powermock.modules.junit4.PowerMockRunner; | |
@RunWith(PowerMockRunner.class) | |
@PrepareForTest(Util.class) | |
public class UtilTest | |
{ | |
@Test | |
public void many_free_memory() throws Exception { | |
Runtime runtimeMock = mock(Runtime.class); | |
when(runtimeMock.freeMemory()).thenReturn((long) 800); | |
when(runtimeMock.totalMemory()).thenReturn((long) 1000); | |
PowerMockito.mockStatic(Runtime.class); | |
PowerMockito.when(Runtime.getRuntime()).thenReturn(runtimeMock); | |
assertThat(Util.isMemoryEnough(), is(true)); | |
} | |
@Test | |
public void no_free_memory() throws Exception { | |
Runtime runtimeMock = mock(Runtime.class); | |
when(runtimeMock.freeMemory()).thenReturn((long) 0); | |
when(runtimeMock.totalMemory()).thenReturn((long) 1000); | |
PowerMockito.mockStatic(Runtime.class); | |
PowerMockito.when(Runtime.getRuntime()).thenReturn(runtimeMock); | |
assertThat(Util.isMemoryEnough(), is(false)); | |
} | |
@Test | |
public void downloadInFile_channel_was_invoked() throws Exception { | |
InputStream stream = new ByteArrayInputStream("Good luck Mockito!".getBytes()); | |
URL urlMock = PowerMockito.mock(URL.class); | |
PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(urlMock); | |
when(urlMock.openStream()).thenReturn(stream); | |
FileOutputStream outputMock = mock(FileOutputStream.class); | |
when(outputMock.getChannel()).thenReturn(mock(FileChannel.class)); | |
PowerMockito.whenNew(FileOutputStream.class).withAnyArguments().thenReturn(outputMock); | |
Util.downloadInFile("http://www.google.com", "google.html"); | |
verify(outputMock).getChannel(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment