package com.calclab.suco.examples.ioc;
import static org.mockito.Mockito.*;
import org.junit.Test;
import com.calclab.suco.testing.ioc.MockContainer;
/**
* This example shows how to use the MockContainer to create components with all
* its dependencies mocked.
*
* MockContainer is a special type of container that always returns a mocked
* instance. We can use the create method in this container to create instances
* with all its dependencies (constructor parameters) filled with mock instances
*/
public class ComponentTestingExample {
/**
* A simple component that calls a service
*/
public static class Component {
private final Service service;
public Component(final Service service) {
this.service = service;
}
public String getMessage() {
return service.getMessage();
}
}
/**
* A simple service that we will mock
*/
public static class Service {
public String getMessage() {
return "a message";
}
}
/**
* We want to verify that a component always call "getMessage" on its
* service when we call the getMessage method on the component
*/
@Test
public void componentShouldCallServiceWhenGetMessage() {
final MockContainer container = new MockContainer();
final Component component = container.create(Component.class);
final Service mockedService = container.getInstance(Service.class);
// perform the call
component.getMessage();
// verify that component called the getMessage method on the mock
// see mockito (mockito.googlecode.com) for more info about how mockito
// works
verify(mockedService, times(1)).getMessage();
}
}