简体   繁体   English

单元测试状态

[英]Unit testing the State

I am trying to fetch data from SharedPreferences during initState() and test it. 我正在尝试在initState()期间从SharedPreferences中获取数据并对其进行测试。 If I simply set private variable inside the state without invoking setState(), view is not updated. 如果仅在状态内设置私有变量而不调用setState(),则视图不会更新。

If I try to wrap setting variables inside setState() my test will break with null pointer at setState() method. 如果我尝试将设置变量包装在setState()中,则测试将在setState()方法中使用空指针中断。

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

Here is my initState() 这是我的initState()

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

here is the test 这是测试

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());
});

I feel there has to be an easier way of doing this. 我觉得必须有一种更简单的方法来做到这一点。

Use SharedPreferences.setMockInitialValues to initialize SharedPreferences with values for testing. 使用SharedPreferences.setMockInitialValues初始化带有测试值的SharedPreferences Then you don't need to mock it yourself. 然后,您无需自己模拟它。

I don't think unit testing the behavior of initState is the right way to achieve your code coverage goals. 我认为单元测试initState的行为不是实现代码覆盖率目标的正确方法。 A State is tied to a StatelessWidget . StateStatelessWidget绑定。 The public API of the StatelessWidget is its constructor arguments (input) and the render objects it produces (output). StatelessWidget的公共API是其构造函数参数(输入)和它产生的渲染对象(输出)。 Nobody should be calling protected methods of a State like initState except for Flutter itself. 除了Flutter本身,没有人可以调用诸如initState之类的State受保护方法。

I suggest you take a look at the Flutter unit tests and see if you can write tests that are more at that level, eg icon button test . 我建议您看一下Flutter单元测试,看看是否可以编写更高级别的测试 ,例如icon button test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM