[英]How do you mock classes that are used in a service that you're trying to unit test using JUnit + Mockito
我想為使用/依賴於另一個類的服務編寫單元測試。 我想做的是模擬依賴類的行為(相對於該類的實例)。 被測試的服務方法在內部使用了依賴類(即,沒有將依賴類的實例傳遞給方法調用),例如,我有一個要測試的服務方法:
import DependentClass;
public class Service {
public void method() {
DependentClass object = new DependentClass();
object.someMethod();
}
}
在我對Service method()的單元測試中,我想在DependentClass實例上模擬someMethod(),而不是讓它使用真實的實例。 我該如何在單元測試中進行設置?
我看過的所有示例和教程都顯示了模擬對象實例,這些實例實例已傳遞到要測試的方法中,但是我還沒有看到任何東西顯示出如何模擬類而不是對象實例 。
Mockito可以做到嗎(肯定是)?
使用Powermockito
框架和whenNew(...)
方法很容易。 測試示例如下:
@Test
public void testMethod() throws Exception {
DependentClass dependentClass = PowerMockito.mock(DependentClass.class);
PowerMockito.whenNew(DependentClass.class).withNoArguments().thenReturn(dependentClass);
Service service = new Service();
service.method();
}
希望能幫助到你
這是設計不良的問題。 您始終可以從包私有構造函數中獲取參數。 您的代碼應執行以下操作:
public class Service {
DependentClass object;
public Service(){
this.object = new DependentClass();
}
Service(DependentClass object){ // use your mock implentation here. Note this is package private only.
object = object;
}
public void method() {
object.someMethod();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.