Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mockito and Dependency Injection
public class Example {
private Delegate delegate;
Example(Delegate delegate) {
this.delegate = delegate;
}
public void doIt() {
delegate.execute();
}
}
@RunWith(MockitoJUnitRunner.class)
public class ExampleTest {
@Mock
Delegate delegateMock;
@InjectMocks
Example example;
@Test
public void testDoIt() {
example.doIt();
verify(delegateMock).execute();
}
}
@Component("example")
public class Example {
@Autowired
private Delegate delegate;
public void doIt() {
delegate.execute();
}
}
@Named("example")
public class Example {
private Delegate delegate;
@Inject
void setDelegate(Delegate delegate) {
this.delegate = delegate;
}
public void doIt() {
delegate.execute();
}
}
@matsev

This comment has been minimized.

Copy link
Owner Author

matsev commented Feb 25, 2012

The code in this gist shows how Mockito can be used to simplify the dependency injection when writing unit tests. For details, read the blog post at http://blog.jayway.com/2012/02/25/mockito-and-dependency-injection/ .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.