1

I have developed a package in flutter, and wanted to test it, which makes a network call. As we know that all network request while testing will return 404, and such HTTP reqeust needs to be mocked. However its also possible to use the orginal HTTP clients instead of mocking or getting 404. https://github.com/flutter/flutter/issues/19086#issuecomment-402639134

How do we do that ?

I have tried this :


main(){
  TestWidgetsFlutterBinding.ensureInitialized();
  HttpOverrides.runZoned(() {
    test("Case1: Make HTTP request to an actual server", ()async{
      let a = MyPackage.makesAHTTPRequest();
       expect(a,"hello world"); 
    });

  }, createHttpClient: (SecurityContext c) => new HttpClient(context: c));

}

My URL is working all fine. But it keeps giving me 404.

How do one use real HTTP client, if needed that way?

Anurag Vohra
  • 1,781
  • 12
  • 28

1 Answers1

0

Ok so if any one is facing a similar issue like me use this hack.

You will need to modify your class, in a way that we can inject HTTP clients into it at run time. We will need to modify our test case as such.

import 'package:http/http.dart'; //client is from this pack
Client httpclinet = Client();
var a = MyPackage.makesAHTTPRequest(httpclient);

remove that Httpoverride.runzoned cod, you can pass Client object from http package directly. Some test case will fail, due to fake asynchronous effect, but you can use timeouts to manage those.

You will also need to remove any such statements: TestWidgetsFlutterBinding.ensureInitialized();

In my case I added this line as I was loading files from assets, using packages notation, I referenced them locally and removed above ensureInitalized line as well. [Actually I passed flag to use local notation during testing and package notation otherwise]

Anurag Vohra
  • 1,781
  • 12
  • 28