[英]not able to inject mock using Dagger
我是 Dagger 和 Mockito 的新手。 我正在嘗試在單元測試中使用 Dagger 模塊中定義的構造函數,因此使用默認值創建 object。
這是模塊:
@Module class AutoCloseCountDownTimerModule {
@Provides
@Singleton
fun getAutoCloseCountDownTimer(
userInteractionClient: UserInteractionClient,
rxPositionManager: RxPositionManager
): AutoCloseCountDownTimer {
return AutoCloseCountDownTimer(userInteractionClient, rxPositionManager, 15000, 45000)
}
這就是我嘗試在單元測試中模擬 AutoCloseCountDown class 的方式:
@RunWith(MockitoJUnitRunner.class) 公共 class AutoCloseCountDownTimerTest {
@Mock
private AutoCloseCountDownTimer autoCloseCountDownTimer;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void basicTest() {
final AutoCloseCountDownTimer.Listener mockListener = Mockito.mock(AutoCloseCountDownTimer.Listener.class);
autoCloseCountDownTimer.registerListener(mockListener);
final int expectedValue = 10;
autoCloseCountDownTimer.notifyOnAutoClose(expectedValue);
Mockito.verify(mockListener).onAutoClose(expectedValue);
如何實現 autoclosedCountDownTimer 將在測試中使用匕首預定義的值?
你一般不會嘗試。 在測試中,一般不會將參數注入到被測 object 中,直接通過 new 傳遞。 可以是常規項目或模擬項目。
如果確實需要注入,則需要設置一個模塊,該模塊通過帶有 @Provides 注釋的 function 提供 object,並在實例化 ZA8CFDE6331BD59EB2AC96F14Z 時創建模擬並將其傳遞給參數您還需要使用您不是 mocking 的任何依賴項傳遞地執行此操作。 然后為該模塊和您需要的任何其他模塊創建一個組件,並使用該組件進行注入。 但是如果可能的話,你真的想避免這種情況,單元測試應該是關於測試小塊功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.