2017-06-28 90 views
1

我想在initState()期間從SharedPreferences獲取數據並對其進行測試。 如果我只是在不調用setState()的情況下在狀態內設置私有變量,視圖就不會更新。單元測試狀態

如果我嘗試在setState()中包裝設置變量,我的測試將在setState()方法中用空指針打破 。

NoSuchMethodError: The method 'markNeedsBuild' was called on null. 
Receiver: null 
Tried calling: markNeedsBuild() 

這裏是我的INITSTATE()

initState() { 
    _appRepository.readOnboardingCompleted().then((readValue) { 
    print("read: $readValue"); 
    setState(()=>_onboardingCompleted = readValue); 
}); 
    super.initState(); 
} 

這裏是測試

test(
    'GIVEN app starts WHEN onboarding was completed THEN onboarding is disabled',() { 

    when(mockAppRepository.readOnboardingCompleted()).thenReturn(mockBoolFuture); 
    AppState systemUnderTest = new AppState(mockAppRepository); 
    systemUnderTest.initState(); 
    verify(mockAppRepository.readOnboardingCompleted()); 
}); 

我覺得必須有這樣做的一個簡單的方法。

回答

1

使用SharedPreferences.setMockInitialValues初始化SharedPreferences用於測試的值。那麼你不需要自己嘲笑它。

我不認爲單元測試initState的行爲是實現您的代碼覆蓋率目標的正確方法。 A StateStatelessWidget聯繫在一起。 StatelessWidget的公共API是其構造函數參數(輸入)和它生成(輸出)的渲染對象。除Flutter本身外,沒有人應該調用State的受保護方法,如initState

我建議你看看Flutter單元測試,看看你是否可以編寫更高級的測試,例如: icon button test

+0

據我所知,initState被框架調用,但它仍然處理業務邏輯,所以應該可以測試它的分離。我將在別處嘗試單獨的邏輯。 – robotoaster

+0

分開你的業務邏輯是一個好主意。 –