1

我正在测试一个从 api 获取餐馆列表的 bloc 方法。

这是我的代码:

import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mobile_app_engineer/blocs/merchant_bloc.dart';
import 'package:mobile_app_engineer/repositories/merchant_repository.dart';
import 'package:mockito/mockito.dart';
import 'package:mobile_app_engineer/models/list_merchants_response.dart';

class MockMerchantRepository extends Mock implements MerchantRepository {}

// Generate a MockClient using the Mockito package.
// Create new instances of this class in each test.
void main() {

late MockMerchantRepository mockMerchantRepository;

setUp((){
  mockMerchantRepository = MockMerchantRepository();
});

List<Merchant> merchantList = [
   Merchant object here    
];

blocTest<MerchantBloc, MerchantState>(
   'Check if merchant fetch return correct data',
   build: () {
   when(mockMerchantRepository.fetchMerchants(1)).thenThrow(NetworkError()); <=== in this line main 101
   return MerchantBloc(mockMerchantRepository);
},
  act: (bloc) => bloc.add(GetMerchantsList(1)),
  expect: () => [MerchantInitial(), GetMerchantsListState(merchantList)],
);

}

我收到此错误:

type 'Null' is not a subtype of type 'Future<List<Merchant>>'
package:mobile_app_engineer/repositories/merchant_repository.dart 14:26  
MockMerchantRepository.fetchMerchants
test/api_test/fetch_restaurant_test.dart 101:35                          main.<fn>
package:bloc_test/src/bloc_test.dart 176:25                              testBloc.<fn>

有什么我做错了吗?谢谢

4

1 回答 1

0

找到了解决方案:这是因为 null 安全所以现在我不得不添加 GenerateMocks 来为 api 调用生成一个模拟存储库。

import 'fetch_merchant_test.mocks.dart';

@GenerateMocks([MockMerchantRepository])
void main() {

final mockMerchantRepository = MockMockMerchantRepository();
于 2021-08-03T23:08:42.287 回答