本文介绍了Flutter Widget测试与NetworkImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个窗口小部件和 NetworkImage (到目前为止带有硬编码的网址)。 我想对这个窗口小部件进行测试,但是运行窗口小部件测试时得到了404(URL为100%有效)。 如何制作 NetworkImages 加载自身还是(更好)忽略它们,这样我的测试就不会因为404而失败? I have a Widget with NetworkImage (so far with hard-coded url).I would like to widget test this Widget, but I got 404 when I run widget test (url is 100% valid).How can I make NetworkImages load themselves or (which would be better) ignore them so that my tests won't fail because of 404? 推荐答案在小部件测试中,默认的HTTP客户端已替换,该参数始终返回400s。在 flutter_markdown repo 以及其他几个地方。我曾经将其复制并粘贴到每个项目中,但是我做了足够多次,以至于变得很无聊。In widget tests, the default HTTP client has been replaced with one that always returns 400s. There's a sample on how to do this in the flutter_markdown repo along with couple other places. I used to copy and paste this to every project, but I did it enough times to get quite bored.(我)现在有一个用于此的库,称为 image_test_utils 。您可以使用 provideMockedNetworkImages 方法包装小部件测试,该方法将模拟的HTTP客户端替换为始终返回透明图像的HTTP客户端。 There's now a library for this (by me), called "image_test_utils". You can wrap your widget tests with a provideMockedNetworkImages method, which replaces the mocked HTTP client with one that always returns transparent images. Which in turn makes your tests pass. pubspec.yaml: dev_dependencies: image_test_utils: ^1.0.0 my_image_test.dart: import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:image_test_utils/image_test_utils.dart';void main() { testWidgets('my image test', (WidgetTester tester) async { provideMockedNetworkImages(() async { /// Now we can pump NetworkImages without crashing our tests. Yay! await tester.pumpWidget( MaterialApp( home: Image.network('https://example.com/image.png'), ), ); /// No crashes. }); });} 这篇关于Flutter Widget测试与NetworkImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-27 16:24