felangel / mocktail

A mock library for Dart inspired by mockito
https://pub.dev/packages/mocktail
MIT License
617 stars 81 forks source link

mockNetworkImages should provide a way to test the errorBuilder from Image.network #212

Open DanielFerrariR opened 12 months ago

DanielFerrariR commented 12 months ago

Details: Sometimes, we need to provide an errorBuilder for Image.network, and, at least so far, I didn't see a way to test it without mocking httpClient, which is basically what mockNetworkImages already does.

Expected: mockNetworkImages should have a new option to make the request fail as failed to fetch the image, so Image.Network can use the errorBuilder instead.

I would really appreciate it if someone had a better and simpler way to do it.

enzoftware commented 3 weeks ago

I have implemented the following approach to simulate an image load failure and verify that the appropriate error message and icon are displayed when the image fails to load:


// A mock class for simulating HTTP client behavior during testing
class MockHttpClient extends Mock implements HttpClient {}

...

testWidgets('displays error message when image fails to load',
    (WidgetTester tester) async {

  // Simulate a failure in retrieving the image by throwing an exception
  when(
    () => httpClient.getUrl(
      Uri.parse(
        'https://image.tmdb.org/t/p/w500/invalid_path.jpg',
      ),
    ),
  ).thenThrow(Exception());

  // Use HttpOverrides to replace the default HTTP client with our mocked client
  await HttpOverrides.runZoned(
    () async {
      // Build the widget with an invalid image path to simulate a failed load
      await tester.pumpWidget(
        const MaterialApp(
          home: Scaffold(
            body: TMDBImage(
              path: '/invalid_path.jpg', // Invalid path to trigger errorBuilder
              width: 150,
              height: 225,
            ),
          ),
        ),
      );

      // Simulate a frame to allow the image to attempt loading
      await tester.pump();

      // Verify that the error icon and message are displayed when the load fails
      expect(find.text('Error'), findsOneWidget); // Check if "Error" text appears
      expect(find.byIcon(Icons.error_outline), findsOneWidget); // Check if error icon appears
    },
    createHttpClient: (_) => httpClient, // Replace default client with mock
  );
});