Testing methods that make http requests

前端 未结 7 1343
悲哀的现实
悲哀的现实 2021-02-09 01:31

I have some methods in my app that make http requests. Is there a good way to simulate network failures and bad responses for the unit tests?

7条回答
  •  难免孤独
    2021-02-09 02:14

    What we do in this situation is abstract the layer that's making the call. Instead of having your logic directly make the http request, have your code call a function. Within that function can be something like:

    if (in_test) {
       response = get_test_response();
    } else {
       response = make_http_request();
    }
    

    Then you can have your unit tests set some value accessible by the get_test_response() function. This way you can programatically change what the result of that call will be.

提交回复
热议问题