Skip to content
This repository has been archived by the owner on Oct 2, 2024. It is now read-only.

What's the best way to generate a fake response to write unit tests? #263

Open
GP4cK opened this issue Feb 25, 2021 · 3 comments
Open

What's the best way to generate a fake response to write unit tests? #263

GP4cK opened this issue Feb 25, 2021 · 3 comments

Comments

@GP4cK
Copy link

GP4cK commented Feb 25, 2021

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?

@comigor
Copy link
Owner

comigor commented Feb 28, 2021

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.

@GP4cK
Copy link
Author

GP4cK commented Feb 28, 2021

Thanks a lot @comigor. Shall we close this now or we wait for the team's answer?

@comigor
Copy link
Owner

comigor commented Mar 1, 2021

I've send this link to them asking if they have any plans. Let's keep this open and I'll remember to update!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants