Created
December 26, 2016 20:06
-
-
Save lipelopeslage/d672d03b50890ea6a4ed690bb5934baa to your computer and use it in GitHub Desktop.
Simple unit testing with JUnit and Mockito
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
import org.junit.Assert; | |
import org.junit.Before; | |
import org.junit.Rule; | |
import org.junit.Test; | |
import org.junit.runner.RunWith; | |
import org.mockito.Mock; | |
import org.mockito.Mockito; | |
import org.mockito.runners.MockitoJUnitRunner; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.when; | |
/** | |
* Created by lipelopeslage on 12/26/16. | |
*/ | |
@RunWith(MockitoJUnitRunner.class) | |
public class JUnitTestCaseOne { | |
private String name; | |
//instancia mockavel de um objeto | |
private Methods methods = mock(Methods.class); | |
@Mock // essa annotation cria uma instancia mockavel como a de cima, mas graças a annotation @RunWith(MockitoJUnitRunner.class) | |
private OtherMethods otherMethods; | |
// configurar valores antes dos testes | |
@Before | |
public void setUp(){ | |
this.name = "Felipe"; | |
when(methods.showMessage()).thenReturn("This is not a message"); | |
} | |
@Test | |
public void metodoQualquer(){ | |
Assert.assertEquals("2 dividido por 2 deveria ser 1.", 1, 2/2); | |
} | |
@Test | |
public void checaNome(){ | |
Assert.assertEquals("O nome deveria ser "+this.name, "Felipe", "Felipe"); | |
} | |
@Test | |
public void quandoMostrarResultados(){ | |
Assert.assertEquals("This is not a message", methods.showMessage()); | |
} | |
@Test | |
public void retornaDobro(){ | |
when(methods.showDouble(5)).thenReturn(10); | |
when(methods.showDouble(10)).thenReturn(10); | |
Assert.assertEquals(10, methods.showDouble(10)); | |
} | |
@Test | |
public void mostraCinco(){ | |
when(methods.showFive()).thenReturn(5); | |
Assert.assertEquals(5, methods.showFive()); | |
} | |
@Test | |
public void mostraDez(){ | |
when(otherMethods.showTen()).thenReturn(10); | |
Assert.assertEquals(10, otherMethods.showTen()); | |
} | |
} | |
class Methods{ | |
public String showMessage(){ | |
return "This is a message"; | |
} | |
public int showFive(){ | |
System.out.println("testando"); | |
return 5; | |
} | |
public int showDouble(int n){ | |
return n * 2; | |
} | |
} | |
class OtherMethods{ | |
public int showTen(){ | |
return 10; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
REFs:
http://www.qualister.com.br/blog/criando-mocks-com-mockito-parte-1-introducao
http://www.vogella.com/tutorials/Mockito/article.html#mock-object-generation
http://blog.caelum.com.br/facilitando-seus-testes-de-unidade-no-java-um-pouco-de-mockito/