You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Mocktail模拟WeatherRepository时遇No method stub错误求助

解决Mocktail模拟WeatherRepository时的"Bad state"错误

错误原因

你当前代码里的mockWeatherRepository是真实的WeatherRepository实例,而非你定义的MockWeatherRepository模拟类实例。当你在when()中调用mockWeatherRepository.getCurrentWeather()时,实际执行的是真实类的方法,Mocktail无法捕获这个调用,因此抛出Bad state: No method stub was called from within when()错误。

修复步骤

  1. 将mockWeatherRepository的类型改为MockWeatherRepository
  2. 在setUp中初始化模拟实例,而非真实的WeatherRepository
  3. 确保when()针对模拟实例的方法进行桩定义

修复后的完整测试代码

import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:weather_app/bloc/weather_bloc.dart';
import 'package:weather_app/data/repository/weather_repository.dart';
import 'package:weather_app/models/weather_model.dart';
import 'package:bloc_test/bloc_test.dart';

class MockWeatherRepository extends Mock implements WeatherRepository {}

void main() {
  late MockWeatherRepository mockWeatherRepository;

  setUp(() {
    // 初始化模拟实例,而非真实Repository
    mockWeatherRepository = MockWeatherRepository();
  });

  String cityName = "New Delhi";
  WeatherModel weather = WeatherModel(
      currentTemp: 20.0,
      currentSky: 'Rain',
      currentPressure: 10,
      currentWindSpeed: 20.0,
      currentHumidity: 10);

  blocTest(
    'Get weather',
    build: () {
      // 针对模拟实例的方法定义桩
      when(() => mockWeatherRepository.getCurrentWeather(cityName))
          .thenAnswer((_) async => weather);

      return WeatherBloc(mockWeatherRepository);
    },
    act: (bloc) => bloc.add(WeatherFetched()),
    expect: () => [
      isA<WeatherLoading>(),
      isA<WeatherSuccess>()
    ],
  );
}

额外说明

  • 你之前定义的MockWeatherRepository类没有被实际使用,这是核心问题
  • 不需要再初始化WeatherDataProvider,因为我们直接模拟了Repository层,跳过了底层数据提供者的依赖

内容的提问来源于stack exchange,提问作者Anish Hemachandran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:33:30