我剛剛開始使用Mockito對Android進行單元測試 - 您如何獲得您正在測試的類使用模擬類/對象而不是常規類/對象?使用模擬對象
Q
使用模擬對象
0
A
回答
0
通過注入的依賴:
public class ClassUnderTest
private Dependency dependency;
public ClassUnderTest(Dependency dependency) {
this.dependency = dependency;
}
// ...
}
...
Dependency mockDependency = mock(Dependency.class);
ClassUnderTest c = new ClassUnderTest(mockDependency);
你也可以使用一個setter注入依賴,甚至直接注射使用@Mock
和@InjectMocks
註釋(讀the javadoc對於他們是如何工作的詳細解釋私人領域)。
1
您可以對編寫測試的類使用@InjectMocks。
@InjectMocks private EmployManager manager;
然後你可以使用@Mock爲你嘲笑的類。這將是依賴類。
@Mock private EmployService service;
然後寫一個設置方法,使可用於您的測試的東西。
@Before public void setup() throws Exception { manager = new EmployManager(); service = mock(EmployService.class); manager.setEmployService(service); MockitoAnnotations.initMocks(this); }
然後寫你的測試。
@Test
public void testSaveEmploy() throws Exception {
Employ employ = new Employ("u1");
manager.saveEmploy(employ);
// Verify if saveEmploy was invoked on service with given 'Employ'
// object.
verify(service).saveEmploy(employ);
// Verify with Argument Matcher
verify(service).saveEmploy(Mockito.any(Employ.class));
}
相關問題
- 1. Dillemma使用模擬對象
- 2. 模擬對象
- 3. 模擬對象
- 4. 用途()模擬對象
- 5. 使用簡單模擬對象
- 6. R:使用日期模擬ts對象
- 7. 模擬對象翻倒使用jQuery
- 8. Junit的使用模擬對象
- 9. 如何使用PHPUnit模擬SimpleXMLElement對象?
- 10. 使用Mockito模擬日期對象
- 11. 使用Matchers.any()來匹配模擬對象
- 12. 我可以使用模擬對象來模擬串口嗎?
- 13. junit模擬對象
- 14. 模擬對象C++
- 15. 模擬WP_REST_Request對象
- 16. 模擬C++對象
- 17. 從部分模擬對象返回模擬對象不工作
- 18. 如何在模擬對象內創建一個模擬對象?
- 19. 如何模擬一個模擬對象返回的對象?
- 20. 使用Rhino Mock模擬包含子對象的對象
- 21. 使用模擬對象和實際對象切換項目的模式
- 22. 模擬對象的標準
- 23. 模擬NHibernate的IQueryOverOrderBuilder對象
- 24. 模擬CGLIB增強對象
- 25. 模擬對象的創建
- 26. 模擬對象和接口
- 27. Java對象模擬R data.frame
- 28. Python模擬依賴對象
- 29. 模擬參考對象
- 30. 模擬對象數據
你能否提供一個答案http://stackoverflow.com/questions/18201643/mock-injection-using-mockito-android。謝謝 – Traxex1909