Last active
March 4, 2018 14:18
-
-
Save ValeriusGC/b5fe822d6d3abfe43cf86c42d784b789 to your computer and use it in GitHub Desktop.
This show how to test Event Handlers with JUnit & 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.Test; | |
import org.mockito.ArgumentCaptor; | |
import static org.junit.Assert.assertEquals; | |
import static org.mockito.Mockito.mock; | |
import static org.mockito.Mockito.verify; | |
class PizzaJava { | |
private final String name; | |
public PizzaJava(String name) { | |
this.name = name; | |
} | |
public String getName() { | |
return name; | |
} | |
} | |
class PizzaServiceJavaAgain { | |
public interface PizzaEventJava { | |
void pizzaAvailable(PizzaJava pizza); | |
} | |
PizzaEventJava listener = null; | |
public void orderPizza( String name) { | |
if(listener != null) { | |
listener.pizzaAvailable(new PizzaJava(name)); | |
} | |
} | |
} | |
public class EventHandlerTest { | |
@Test | |
public void testEvent() { | |
String pizzaName = "MargaritaJava"; | |
PizzaServiceJavaAgain service = new PizzaServiceJavaAgain(); | |
PizzaServiceJavaAgain.PizzaEventJava event = mock( PizzaServiceJavaAgain.PizzaEventJava.class ); | |
service.listener = event; | |
service.orderPizza(pizzaName); | |
ArgumentCaptor<PizzaJava> captor = ArgumentCaptor.forClass( PizzaJava.class ); | |
verify( event ).pizzaAvailable( captor.capture() ); | |
PizzaJava capturedPizza = captor.getValue(); | |
assertEquals( pizzaName, capturedPizza.getName() ); | |
} | |
} | |
//------------------------------------------------------------------------------------------------------------- | |
{in pom.xml} | |
<dependencies> | |
<dependency> | |
<groupId>junit</groupId> | |
<artifactId>junit</artifactId> | |
<version>4.12</version> | |
<scope>test</scope> | |
</dependency> | |
<dependency> | |
<groupId>org.mockito</groupId> | |
<artifactId>mockito-core</artifactId> | |
<version>2.7.13</version> | |
<scope>test</scope> | |
</dependency> | |
</dependencies> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment