如何在Flutter中测试用于更新PublishSubject或BehaviorSubject对象(RxDart)的异步函数

时间:2019-05-30 22:08:58

标签: flutter dart rxdart

我已经学习了Flutter几周了,到目前为止,我来自Android背景,我很喜欢它,而且我也很高兴发现Flutter从一开始就考虑到测试的设计。但是,在运行以下测试时遇到了问题。

main() => {
  test('test get popular repos', () async {
    final testOwner = Owner(1010, "testLink");
    final testRepo =
        Repo(101, testOwner, "testRepo", "description", 'htmlUrl', 500);
    final testRepoResponse = RepoResponse(List.from([testRepo]), null);
    final uiModel = PopRepo(testRepo.owner.avatarUrl, testRepo.name,
        testRepo.description, "Stars: ${testRepo.stargazersCount}");
    final searchData = SearchData(List.from([uiModel]), null);

    final Repository mockRepository = _mockRepository();

    when(mockRepository.getPopularReposForOrg("org"))
        .thenAnswer((_) => Future.value(testRepoResponse));

    final repoSearchBloc = RepoSearchPageBloc(mockRepository);
    await repoSearchBloc.getPopularRepos("org");


    await expectLater(repoSearchBloc.resultSubject.stream, emits(searchData));
  }),
};

class _mockRepository extends Mock implements Repository {}

我的RepoSearchBloc从存储库中获取数据,并将其转换为Ui模型。最后,它将现在支持UI的数据发布到Subject

这是RepoSearchBloc中正在测试的方法

getPopularRepos(String org) async {
if (org == null || org.isEmpty)
  return resultSubject.add(SearchData(List(), null));
RepoResponse response = await _repository.getPopularReposForOrg(org);
if (response.error == null) {
  List<Repo> repoList = response.results;
  repoList.sort((a, b) => a.stargazersCount.compareTo(b.stargazersCount));
  var uiRepoList = repoList
      .map((repo) => PopRepo(repo.owner.avatarUrl, repo.name,
          repo.description, "Stars: ${repo.stargazersCount}"))
      .take(3)
      .toList();
  resultSubject.add(SearchData(uiRepoList, null));
} else {
  ErrorState error = ErrorState(response.error);
  resultSubject.add(SearchData(List(), error));
}

运行测试时,无论我用BehaviorSubject还是PublishSubject做什么,我都会不断收到此消息:

ERROR: Expected: should emit an event that <Instance of 'SearchData'>
  Actual: <Instance of 'BehaviorSubject<SearchData>'>
   Which: emitted * Instance of 'SearchData'

有什么想法可以使该测试通过吗?

1 个答案:

答案 0 :(得分:0)

最终在Flutter Glitter community的用户Nico @Rodsevich的帮助下解决了这个问题

无论如何还是根据他的建议使用await for

我想出了以下通过的解决方案

    await for (var emittedResult in repoSearchBloc.resultSubject.stream) {
      expect(emittedResult.results[0].repoName, testRepo.name);
      return;
    }

RxDart库具有一些主题测试for reference,但是我的主题被异步发布到他们的测试用例中去,因此该解决方案最终正是我所需要的。

当我将Async移入预期参数时,@ Abion47的注释似乎也可以完成

expectLater( (await repoSearchBloc.resultSubject.stream.first as SearchData).results[0].repoName, testRepo.name);