简体   繁体   English

单元测试一肘

[英]Unit Testing a Cubit

This is my first effort at testing my Cubit class, so please bear with me as I am completely out of ideas after trying for many hours.这是我第一次尝试测试我的Cubit class,所以请多多包涵,因为我在尝试了好几个小时后完全没有想法。

I'm trying to test a simple cubit that looks like this:我正在尝试测试一个看起来像这样的简单肘尺:

@injectable
class ResetPasswordCubit extends Cubit<ResetPasswordState> {

  ResetPasswordCubit() : super(ResetPasswordInitial());

  void attemptPasswordReset({required ResetPasswordParams params}) async {
    emit(ResetPasswordLoading());
    emit(ResetPasswordLoaded());
  }
}

All I want to do is to verify that both of these states were emitted in order.我想要做的就是验证这两种状态是否按顺序发出。 According to the docs , there are a couple of ways to do this, but I'm not even sure which one I should be using.根据文档,有几种方法可以做到这一点,但我什至不确定我应该使用哪一种。 I would prefer to use the unit test, although I've tried both.我更愿意使用单元测试,尽管我都试过了。 Here is what I have:这是我所拥有的:

class MockResetPasswordCubit extends MockCubit<ResetPasswordState>
    implements ResetPasswordCubit {}

@GenerateMocks([ResetPassword])
void main() {
  late MockResetPassword mockResetPassword;
  late MockResetPasswordCubit cubit;
  late ResetPasswordParams params;

  setUp(() {
    mockResetPassword = MockResetPassword();
    cubit = MockResetPasswordCubit();
    params = const ResetPasswordParams(
        pin: "1234", password: "hello", confirmPassword: "hello");
    when(mockResetPassword.call(params))
        .thenAnswer((_) async => const Right(ResetPasswordResult.validated));
  });

  blocTest<ResetPasswordCubit, ResetPasswordState>(
      'when attempt to validate password is made then loading state is emitted',
      build: () => cubit,
      act: (cubit) => cubit.attemptPasswordReset(params: params),
      expect: () => [ResetPasswordLoading(), ResetPasswordLoaded()]);
}

And this is the error that gets displayed:这是显示的错误:

Expected: [Instance of 'ResetPasswordLoading', Instance of 'ResetPasswordLoaded']预期:[“ResetPasswordLoading”实例,“ResetPasswordLoaded”实例]
Actual: []实际的: []
Which: at location [0] is [] which shorter than expected其中:位置 [0] 是 [],比预期的要短

I'm really out of ideas, so hoping someone can set me straight.我真的没有想法,所以希望有人可以让我直截了当。 Thanks.谢谢。

It seems that you are trying to test the ResetPasswordCubit but what you do is mock it, hence it is not possible to test the actual cubit's behaviour.似乎您正在尝试测试ResetPasswordCubit但您所做的是模拟它,因此无法测试实际的 cubit 行为。

Just do not mock the cubit you want to test and create an instance of it:只是不要模拟你想要测试的手肘并创建它的一个实例:

blocTest<ResetPasswordCubit, ResetPasswordState>(
  'when attempt to validate password is made then loading state is emitted',
  build: () => ResetPasswordCubit(), // <-- Creating an instance of Cubit
  act: (cubit) => cubit.attemptPasswordReset(params: params),
  expect: () => [ResetPasswordLoading(), ResetPasswordLoaded()],
);

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

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