差異處
這裏顯示兩個版本的差異處。
下次修改 | 前次修改 | ||
java:junit:mockito:annotations [2021/02/15 15:21] tony 建立 |
java:junit:mockito:annotations [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
- | ====== Mockito with annotations ====== | + | {{tag>java mockito}} |
+ | ====== Mockito - Mockito with annotations ====== | ||
===== Introduction ===== | ===== Introduction ===== | ||
- | 為了減少大家重複撰寫mock、spy或captor等語法,Mockito提供了annotation去解決這個問題。 | + | 為了減少大家重複撰寫mock、spy或captor等語法,Mockito提供了annotation去解決這個問題。[[https://www.baeldung.com/mockito-annotation|此篇]]教學已經寫的非常淺顯易懂,我只針對它不足的部分做補充。 |
+ | ===== Enable Mockito Annotations ===== | ||
+ | 要使用這個功能之前,必須要去啟用它,最常使用的方式就是直接使用MockitoJUnitRunner當Runner: | ||
+ | <code java> | ||
+ | @RunWith(MockitoJUnitRunner.class) | ||
+ | public class CheckConnectionCommandTest { | ||
+ | // skip | ||
+ | } | ||
+ | </code> | ||
+ | 假如你已經使用了PowerMockRunner或SpringJUnit4ClassRunner當Runner,你就要從以下兩個方法選一個出來用。一個是在testcase setup去初始化: | ||
+ | <code java> | ||
+ | @Before | ||
+ | public void init() { | ||
+ | MockitoAnnotations.initMocks(this); | ||
+ | } | ||
+ | </code> | ||
+ | 另外一個就是透過@Rule的方式: | ||
+ | <code java> | ||
+ | @Rule | ||
+ | public MockitoRule initRule = MockitoJUnit.rule(); | ||
+ | </code> | ||
+ | ===== Reference ===== | ||
+ | * [[https://www.baeldung.com/mockito-annotations|Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks]] | ||
+ | ===== ===== | ||
+ | ---- | ||
+ | \\ | ||
+ | ~~DISQUS~~ |