Skip to content

Instantly share code, notes, and snippets.

@mtov
Last active August 19, 2021 19:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtov/f7781e3f164a62c85cf4294271b9c2fd to your computer and use it in GitHub Desktop.
Save mtov/f7781e3f164a62c85cf4294271b9c2fd to your computer and use it in GitHub Desktop.
Exemplo de Mocks - usando Mockito
public class Book {
private String titulo;
public Book(String titulo) {
this.titulo = titulo;
}
public String getTitulo() {
return titulo;
}
}
import org.json.JSONObject;
public class BookSearch {
BookService rbs;
public BookSearch(BookService rbs) {
this.rbs = rbs;
}
public Book getBook(int isbn) {
String json = rbs.search(isbn);
JSONObject obj = new JSONObject(json);
String titulo = (String) obj.get("titulo");
return new Book(titulo);
}
}
import static org.junit.Assert.*;
import org.junit.*;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyInt;
class BookConst {
public static final String ESM = "{ \"titulo\": \"Eng Soft Moderna\" }";
public static final String NULLBOOK = "NULL";
}
public class BookSearchTest {
BookService service;
@Before
public void init() {
service = Mockito.mock(BookService.class);
when(service.search(anyInt())).thenReturn(BookConst.NULLBOOK);
when(service.search(1234)).thenReturn(BookConst.ESM);
}
@Test
public void testGetBook() {
BookSearch bs = new BookSearch(service);
String titulo = bs.getBook(1234).getTitulo();
assertEquals("Eng Soft Moderna", titulo);
}
}
public interface BookService {
String search(int isbn);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment