Riverpod依赖Provider测试问题:overrideWithValue不可用
解决方案
对于用@Riverpod注解的类Provider(比如你的DataEntryController),确实无法使用overrideWithValue()——这类Provider基于StateNotifier实现,只能通过overrideWith()替换其构建逻辑。你可以通过以下两种方式正确覆写:
方法一:重写build方法返回测试状态
在overrideWith()的回调中,返回自定义的_$DataEntryController子类,重写build()方法直接返回预设的测试状态:
test('getItersectionsOnAxes', () { final overrides = <Override>[ dataEntryControllerProvider.overrideWith(() => _$DataEntryController() { @override DataEntryModel build() { return const DataEntryModel( objective: Objectives.max, objectiveFunction: [180, 90], operators: [Operators.geq, Operators.geq, Operators.geq], constraints: [ [6, 8, 48], [1, 0, 6], [0, 1, 4], ], ); } }), ]; final container = createProviderContainer(overrides: overrides); final intersections = container.read(getItersectionsOnAxesProvider); expect(intersections, [const Point<double>(6 / 1, 0)]); });
方法二:直接设置初始状态
如果你不想子类化,可直接实例化_$DataEntryController并设置state(Riverpod生成的类默认支持这种方式):
test('getItersectionsOnAxes', () { final testModel = const DataEntryModel( objective: Objectives.max, objectiveFunction: [180, 90], operators: [Operators.geq, Operators.geq, Operators.geq], constraints: [ [6, 8, 48], [1, 0, 6], [0, 1, 4], ], ); final overrides = <Override>[ dataEntryControllerProvider.overrideWith(() => _$DataEntryController()..state = testModel), ]; final container = createProviderContainer(overrides: overrides); final intersections = container.read(getItersectionsOnAxesProvider); expect(intersections, [const Point<double>(6 / 1, 0)]); });
关键注意点
- 不要直接返回
DataEntryController(),它会执行原有的build()逻辑,无法覆盖为测试状态;必须重写build()或直接设置state。 - 确保
DataEntryModel是不可变类型(用const修饰),避免测试中状态意外变更。
内容的提问来源于stack exchange,提问作者OppositeDragon
相关产品推荐
相关产品推荐

