artemis
artemis copied to clipboard
What's the best way to generate a fake response to write unit tests?
Often, in my code, I have something like this:
Query(
options: QueryOptions(
document: ItemsQuery().document
variables: ItemsArguments(...),
),
builder: (result, { refetch, fetchMore }) {
// skipping error handling etc.
final data = ItemsQuery().parse(result.data);
return MyWidget(data);
},
);
When I want to write a test for MyWidget
, I need to generate data to pass as an input. I can think of several solutions:
The first one is to manually create a json and do something like:
final json = [{
'id': 'id0',
'title': 'Title 0',
'description': 'Description 0',
}, {
'id': 'id1',
// ...
}];
final data = ItemsQuery().parse(json);
await WidgetTestHelper.generateApp(tester, MyWidget(data));
expect(...);
This works ok but people may make mistakes when writing the JSON. I've already seen this happening in my team.
The other solution is to do something like:
final json = [
(Items$Query$Item()
..id = 'id0'
..title = 'Title 0'
..description = 'Description 0').toJson()
];
final data = ItemsQuery().parse(json);
//...
This is slightly better because the editor will catch typos or attributes that do no exist.
But it gets really tedious when there are nested object in the response.
Ex:
Items$Query$Item()
..id = 'id0'
..title = 'Title 0'
..description = 'Description 0
..createdBy = (Items$Query$Item$CreatedBy()
..username = 'Alice'
..address = (Items$Query$Item$CreatedBy$Address() // <- this is very long
// ...
Do you guys have a better way of doing this?
Hi @GP4cK!
In my work, for unit tests, we're doing your second example. Although kinda boring to write, it is surely safer than the first option. One of the teams is working on a code generator solution to mock those classes generated by Artemis, though. I'll reach them to see if they plan to ship it as opensource.
Thanks a lot @comigor. Shall we close this now or we wait for the team's answer?
I've send this link to them asking if they have any plans. Let's keep this open and I'll remember to update!