我试图在 initState() 期间从 SharedPreferences 获取数据并测试它。 如果我只是在状态内设置私有(private)变量而不调用 setState(), View 不会更新。
如果我尝试将设置变量包装在 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());
});
我觉得必须有一种更简单的方法来做到这一点。
最佳答案
使用SharedPreferences.setMockInitialValues
使用测试值初始化 SharedPreferences
。那么你不需要自己 mock 它。
我认为对 initState
的行为进行单元测试并不是实现代码覆盖率目标的正确方法。 State
与 StatelessWidget
绑定(bind)。 StatelessWidget 的公共(public) API 是它的构造函数参数(输入)和它生成的渲染对象(输出)。除了 Flutter 本身之外,没有人应该调用 State
的 protected 方法,例如 initState
。
我建议你看一下 Flutter 单元测试,看看你是否可以编写更多该级别的测试,例如icon button test .
关于flutter - 单元测试状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44796857/