Comments (7)
@AdrianDev0 As per RESTful standards, usually you should expect the same result from the same endpoint. If not - there might be something wrong with the implementation.
If you need to test different scenarios on the same endpoint, I suggest using dioAdapter.onGet
but per one request/per one response.
from http-mock-adapter.
Hi @LukaGiorgadze, yes absolutely. You are right. A frontend can't handle different structure of a response for the came api request. But how can I handle different values and different status code in the same test for the same URL? for example this test scenario:
- GET Request to http://localhost/cars/1 delivers 404 (not found)
- POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
- GET Request to http://localhost/cars/1 delivers 200 with some cars data
- POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)
Requests 1 and 3 are going to the same path with different responses. Request 2 and 4 too. There is a history (aka recording) mechanism inside http-mock-adapter , isn't it?
Any ideas?
@meltzow You can reconfigure the mock responses after you made your calls like this:
test('test retry mechanism', () async {
const path = 'http://localhost/cars/1';
var data = {'id': 1, 'name': 'mock'};
Response<dynamic> response;
final dioError404 = DioException(
error: {'message': 'error'},
requestOptions: RequestOptions(path: path),
response: Response(
statusCode: 404,
requestOptions: RequestOptions(path: path),
),
type: DioExceptionType.badResponse,
);
final dioError409 = DioException(
error: {'message': 'error'},
requestOptions: RequestOptions(path: path),
response: Response(
statusCode: 409,
requestOptions: RequestOptions(path: path),
),
type: DioExceptionType.badResponse,
);
// 1. GET Request to http://localhost/cars/1 delivers 404 (not found)
dioAdapter.onGet(path, (server) => server.throws(404, dioError404));
dioAdapter.onPost(
path,
(server) => server.reply(201, 'Created'),
data: data,
);
expect(() async => await dio.get(path), throwsA(isA<DioException>()));
// 2. POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
response = await dio.post(path, data: data);
expect(response.statusCode, 201);
expect(response.data, 'Created');
dioAdapter.onGet(
path,
(server) => server.reply(200, data),
);
// 3. GET Request to http://localhost/cars/1 delivers 200 with some cars data
response = await dio.get(path);
expect(response.statusCode, 200);
expect(response.data, data);
// 4. POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)
dioAdapter.onPost(
path,
(server) => server.throws(409, dioError409),
data: data,
);
expect(() async => await dio.post(path), throwsA(isA<DioException>()));
});
If you have a more complex solution I would usually go for a self-storing solution. Create a map in your test var cars = <String, Car>{};
and then make the endpoints general something like this:
dioAdapter.onGet(
path,
(server) => server.reply(
200,
(RequestOptions options) {
final carId = options.path.split('/').last;
return cars[carId];
},
),
);
dioAdapter.onPost(
path,
(server) => server.reply(
201,
(RequestOptions options) {
final carId = options.path.split('/').last;
cars[carId] = options.data;
return 'Created';
},
),
data: data,
);
However, here you would need to introduce a fallback for the cases where the car does not exist (GET) or even already exists (POST). I tried with the approach like this:
dioAdapter.onGet(
path,
(server) {
final carId = path.split('/').last;
if (!cars.containsKey(carId)) {
server.throws(404, dioError404);
return;
}
server.reply(
200,
(RequestOptions options) {
final carId = options.path.split('/').last;
return cars[carId];
},
);
},
);
But it does not work as the guard clause for not-found cars is happening on the registering level and thus only called once (in comparison to the callback for the request). If I'm not mistaken there's at the moment no way to decide if we want to reply or throw an exception only based on the request. The callback would have to be on an entire level higher (the entire request and not just the body).
I'm also not quite sure what the reason behind the history feature of this package is as I currently do not see any benefits. Or is it so that we could easily test the entire call history?
from http-mock-adapter.
Here is a small workaround for returning different status codes with different requests:
final adapter = DioAdapter(dio: dio);
adapter.onGet('foo', (server) {
// Reply with 401 on first response
server.reply(401, (request) {
// Reply with 200 on second response
adapter.onGet('foo', (server) => server.reply(200, 'OK'));
return 'Unauthorized';
});
});
Not very elegant, but I need this for testing an interceptor for a token refresh flow, so the first response must return 401 (access token invalid and must be refreshed) and the second should return 200 (token valid).
A solution could be to allow "enqueuing" response, e.g. like okhttp/mockwebserver: https://github.com/square/okhttp/tree/master/mockwebserver
from http-mock-adapter.
Hi @LukaGiorgadze,
yes absolutely. You are right. A frontend can't handle different structure of a response for the came api request.
But how can I handle different values and different status code in the same test for the same URL?
for example this test scenario:
- GET Request to http://localhost/cars/1 delivers 404 (not found)
- POST Request to http://localhost/cars/1 for creating the car entity (http status 200)
- GET Request to http://localhost/cars/1 delivers 200 with some cars data
- POST Request to http://localhost/cars/1 deliver 409 ("conflict" or something other)
Requests 1 and 3 are going to the same path with different responses. Request 2 and 4 too. There is a history (aka recording) mechanism inside http-mock-adapter , isn't it?
Any ideas?
from http-mock-adapter.
hi @LukaGiorgadze
If I understand RESTful standard correct, there no expectation to have the same result from the same endpoint. It depends from time or better from state at server (perhaps database).
for example: If I do a GET from "http://localhost/cars/1" probably the response contains a car entity (with Id 1). But if this car entity was changed or deleted I'will get another response.
How can I test these scenario with http-mock-adapter in one test?
Thank you
from http-mock-adapter.
hi @LukaGiorgadze If I understand RESTful standard correct, there no expectation to have the same result from the same endpoint. It depends from time or better from state at server (perhaps database).
for example: If I do a GET from "http://localhost/cars/1" probably the response contains a car entity (with Id 1). But if this car entity was changed or deleted I'will get another response.
How can I test these scenario with http-mock-adapter in one test? Thank you
Hi @meltzow , thank you for your feedback!
Okay, let's take your example [GET] http://localhost/cars/1
This endpoint potentially can return a different response per different status codes, but not a different response with the same status code (when I'm saying response I mean the structure of the response, not the actual values).
Now imagine, you have a frontend typescript schema that expects a Cars entity with the pre-defined fields for status 200, how correct it will be if you get a different data structure but the same status code 200? Your front end won't understand what to expect and when.
Well, in the above case if you expect breaking changes on the front end, ideally you should version your API by URL. http://localhost/v1/cars/1
from http-mock-adapter.
@meltzow Yeh, that makes sense. Currently, it's not supported, but definitely good to have. I'll keep this issue open. Thank you!
from http-mock-adapter.
Related Issues (20)
- [v0.4.0] collection version conflict between the v0.4.0 and flutter_test HOT 9
- Lower the Dart SDK constraint to 2.15.0
- FullHttpRequestMatcher: not identical data returns success response HOT 3
- Using query parameters in response data generation HOT 2
- use tester.pump rather than Future.delayed to allow tests to run faster HOT 1
- Split up `MockServer` `reply` method into static and dynamic version HOT 11
- http_mock_adapter 0.5.0 conflicts with flutter_test collection version. HOT 8
- Async mocking not possible HOT 1
- Semantic release with github action HOT 2
- Add methods onDownload & onDownloadUri
- Library not compatible with flutter 3.16.0 - incorrect type definition HOT 3
- LDClient.get() was called before init()!
- Ability to mock whole API interface for local development without a need of a server. HOT 2
- Allow timeout simulations in replies HOT 2
- QUESTION: how to use dio.simpleGet HOT 2
- http_mock_adapter-0.4.4/lib/src/mixins/request_handling.dart:32:42: Error: A value of type 'FutureOr<List<int>>' can't be assigned to a variable of type 'List<int>'. HOT 1
- Latest registered callback is called when multiple HTTP methods have been mocked
- TypeError Occurs When Map Data and Headers are Set Together
- Cannot add Response to DioException in server.throws
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from http-mock-adapter.