Created
February 18, 2012 09:26
-
-
Save matsev/1858422 to your computer and use it in GitHub Desktop.
Mockito and Dependency Injection
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
public class Example { | |
private Delegate delegate; | |
Example(Delegate delegate) { | |
this.delegate = delegate; | |
} | |
public void doIt() { | |
delegate.execute(); | |
} | |
} |
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
@RunWith(MockitoJUnitRunner.class) | |
public class ExampleTest { | |
@Mock | |
Delegate delegateMock; | |
@InjectMocks | |
Example example; | |
@Test | |
public void testDoIt() { | |
example.doIt(); | |
verify(delegateMock).execute(); | |
} | |
} |
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
@Component("example") | |
public class Example { | |
@Autowired | |
private Delegate delegate; | |
public void doIt() { | |
delegate.execute(); | |
} | |
} |
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
@Named("example") | |
public class Example { | |
private Delegate delegate; | |
@Inject | |
void setDelegate(Delegate delegate) { | |
this.delegate = delegate; | |
} | |
public void doIt() { | |
delegate.execute(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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/ .