Mockito es un framework de código abierto para crear pruebas unitarias en Java publicado bajo la licencia MIT El framework permite la creación de objetos dobles de prueba (objetos simulados) en pruebas de unidad automatizada para el desarrollo guiado por pruebas (TDD) o desarrollo dirigido por el comportamiento (BDD).
El nombre y el logotipo del marco son un juego de palabras con los mojitos, un tipo de bebida.
Características Mockito permite a los desarrolladores verificar el comportamiento del sistema bajo prueba (SUT) sin establecer expectativas de antemano. Una de las críticas a los objetos mock es que hay un estrecho acoplamiento del código de prueba con el sistema bajo prueba. Mockito intenta eliminar el patrón esperar-ejecutar-verificar eliminando la especificación de expectativas. Mockito también proporciona algunas anotaciones para reducir el código repetitivo.
Orígenes Mockito Empezó por expandir en la sintaxis y funcionalidad de EasyMock.
Ejemplo Consideremos este programa desacoplado de Hola Mundo; podemos probar unitariamente algunas de sus partes, utilizando objetos simulados para otras partes. package org.examples;
import java.io.IOException;
public class HelloApplication {
public static interface Greeter { String getGreeting(String subject); String getIntroduction(String actor);
public static class HelloGreeter implements Greeter { private String hello; private String segmenter;
public HelloGreeter(String hello, String segmenter) { this.hello = hello; this.segmenter = segmenter;
public String getGreeting(String subject) { return hello + " " + subject;
public String getIntroduction(String actor) { return actor+segmenter;
public static interface HelloActable { void sayHello(String actor, String subject) throws IOException;
public static class HelloAction implements HelloActable { private Greeter helloGreeter; private Appendable helloWriter;
public HelloAction(Greeter helloGreeter, Appendable helloWriter) { super(); this.helloGreeter = helloGreeter; this.helloWriter = helloWriter;
public void sayHello(String actor, String subject) throws IOException { helloWriter.append(helloGreeter.getIntroduction(actor)).append(helloGreeter.getGreeting(subject));
public static void main(String... args) throws IOException { new HelloAction(new HelloGreeter("hello", ": "), System.out).sayHello("application", "world");
}application: hello worldEl resultado del lanzamiento de HelloApplication será el siguiente: package org.examples;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
import org.junit.Before; import org.junit.Test;
import org.examples.HelloApplication.HelloActable; import org.examples.HelloApplication.HelloAction; import org.examples.HelloApplication.Greeter;
public class HelloActionUnitTest {
Greeter helloGreeterMock; Appendable helloWriterMock; HelloActable helloAction;
@Before public void setUp() { helloGreeterMock = mock(Greeter.class); helloWriterMock = mock(Appendable.class); helloAction = new HelloAction(helloGreeterMock, helloWriterMock);
@Test public void testSayHello() throws Exception { when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock); when(helloGreeterMock.getIntroduction(eq("unitTest"))).thenReturn("unitTest : "); when(helloGreeterMock.getGreeting(eq("world"))).thenReturn("hi world");
helloAction.sayHello("unitTest", "world");
verify(helloGreeterMock).getIntroduction(eq("unitTest")); verify(helloGreeterMock).getGreeting(eq("world"));
verify(helloWriterMock, times(2)).append(any(String.class)); verify(helloWriterMock, times(1)).append(eq("unitTest : ")); verify(helloWriterMock, times(1)).append(eq("hi world"));
}unitTest : hi worldpackage org.examples;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when;
import org.junit.Before; import org.junit.Test;
import org.examples.HelloApplication.HelloActable; import org.examples.HelloApplication.HelloAction; import org.examples.HelloApplication.Greeter; import org.examples.HelloApplication.HelloGreeter;
public class HelloActionIntegrationTest { HelloActable helloAction; Greeter helloGreeter; Appendable helloWriterMock;
@Before public void setUp() { helloGreeter = new HelloGreeter("welcome", " says "); helloWriterMock = mock(Appendable.class); helloAction = new HelloAction(helloGreeter, helloWriterMock);
@Test public void testSayHello() throws Exception { when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock);
helloAction.sayHello("integrationTest", "universe");
verify(helloWriterMock, times(2)).append(any(String.class)); verify(helloWriterMock, times(1)).append(eq("integrationTest says ")); verify(helloWriterMock, times(1)).append(eq("welcome universe"));
}Utiliza objetos simulados sólo en lugar de las interfaces de Appendable, utiliza las implementaciones reales para otras interfaces (HelloActable y Greeter), y asume implícitamente el siguiente caso de uso: integrationTest says welcome universeComo se puede ver en las declaraciones de importación de las clases HelloActionUnitTest y HelloActionIntegrationTest, es necesario poner algunos jars de Mockito y JUnit en su ruta de clases para poder compilar y ejecutar las clases de prueba.
Véase también
Comportamiento desarrollo conducido Lista de frameworks de pruebas unitarias Pruebas de software
Referencias
Categoría:Pruebas de software