简体   繁体   English

Flutter BLoC 测试

[英]Flutter BLoC Testing

I am using the flutter_bloc library and trying to do unit testing.我正在使用 flutter_bloc 库并尝试进行单元测试。 I am doing this pretty much as explained in this tutorial and it's doing fine.我正在按照本教程中的说明进行此操作,并且效果很好。

However, if a BlocState which extends Equatable (which required) has many properties or large list of items which extends Equatable, as well with their props[] defined as required.但是,如果扩展 Equatable(需要)的 BlocState 具有许多扩展 Equatable 的属性或大量项目列表,以及它们的 props[] 定义为需要。

This makes hard for the expectLater() to match proper emitted states because it tries to match the exact instance with its content and not only the state type or instance of.这使得expectLater()很难匹配正确的发射状态,因为它试图将确切的实例与其内容匹配,而不仅仅是 state 类型或实例。

For example:例如:

Consider the following State class:考虑以下 State class:

class BlocState extends Equatable{
     final List<String> data;
     BlocState({this.data});

     @override
     List<Object> get props => [data];
}

Then for emitted state like this:然后对于像这样发出的 state :

List<String> data = ['Mark', 'Mike', 'John']
BlocState({data: data}); 

This expectLater will fail这个 expectLater 会失败

 expectLater(
    bloc,
    emitsInOrder([BlocState(),]), //This will fail as the state does't equals exactly to the real state
  )

And this one will pass:而这个将通过:

expectLater(
    bloc,
    emitsInOrder([BlocState(data: ['Mark', 'Mike', 'John']),]), //This will pass 
  )

On such simple state it's fine to verify exact content, but if the list will have 100 items how it can be tested?在如此简单的 state 上,可以验证确切的内容,但如果列表将包含 100 个项目,如何对其进行测试?

Is there a way to verify just the instance type without the content?有没有办法只验证没有内容的实例类型?

I'm not sure if this is what you mean, but you could do something like this:我不确定这是否是您的意思,但您可以执行以下操作:

List<String> myData = ['Mark', 'Mike', 'John', 'AddAsManyAsYouLike'];
bloc.add(SomeEvent());

expectLater(
    bloc,
    emitsInOrder([BlocState(data: myData)])
)

Or if you only care about the right type you could use isA<>()或者,如果您只关心正确的类型,您可以使用isA<>()

expectLater(
    bloc,
    emitsInOrder([isA<BlocState>()])
)

I'm a bit late but I had the same question and I found this:我有点晚了,但我有同样的问题,我发现了这个:

List<String> myData = ['Mark', 'Mike', 'John', 'AddAsManyAsYouLike'];
bloc.add(SomeEvent());

expectLater(
    bloc,
    emitsInOrder([
        predicate<BlocState>(
            (state) => 
                state.oneOfMyProperties == 'expected value' &&
                state.anotherProperty == 'another expected value'
        )
    ])
)

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

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