Skip to content

Instantly share code, notes, and snippets.

@matsev
Created February 18, 2012 09:26
Show Gist options
  • Save matsev/1858422 to your computer and use it in GitHub Desktop.
Save matsev/1858422 to your computer and use it in GitHub Desktop.
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
Copy link
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