Baseflow / flutter_cached_network_image

Download, cache and show images in a flutter app
https://baseflow.com
2.44k stars 654 forks source link

Make cached_network_image friendly with widget testing #814

Open darwin-morocho opened 1 year ago

darwin-morocho commented 1 year ago

πŸ— Enhancement Proposal

Currently widget testing for CachedNetworkImage is very difficult and there are some packages for that like https://pub.dev/packages/network_image_mock but I think that could be more easy.

Pitch

class DefaultCacheManager extends CacheManager with ImageCacheManager {
  static const key = 'libCachedImageData';

  static DefaultCacheManager? _instance;

  static DefaultCacheManager? _mockCacheManager;

  factory DefaultCacheManager() {
    _instance ??= _mockCacheManager ?? DefaultCacheManager._();
    return _instance!;
  }

  DefaultCacheManager._() : super(Config(key));
}

@visibleForTesting
Future<void> mockDefaultCacheManager(
  Future Function() cb,
  DefaultCacheManager mockCacheManager,
) {
  DefaultCacheManager._mockCacheManager = mockCacheManager;
  await cb();
  DefaultCacheManager._mockCacheManager = null;
  DefaultCacheManager._instance = null;
}

then in our tests we can use

testWidgets('my test', 
   (tester) async {
    final mock = ....;
    return mockDefaultCacheManager(
      () async {
        /// OUR TEST CODE
      }
    );
    },
);
meg4cyberc4t commented 1 year ago

Very necessary for me. There is no way to make a MockCacheManager and all goldens tests fall with an error. Let's open the BaseCacheManager for export, or will we make an implementation for testing specifically and open it?

selawik commented 4 months ago

Same thing for me, goldens does not work with that. Any update?