marcglasberg / async_redux

Flutter Package: A Redux version tailored for Flutter, which is easy to learn, to use, to test, and has no boilerplate. Allows for both sync and async reducers.
Other
230 stars 41 forks source link

how to handle repository #84

Closed rodrigobastosv closed 4 years ago

rodrigobastosv commented 4 years ago

Hi @marcglasberg , first of all thanks for the great package. I started using and it's great.

I have one question though.

I'm having trouble on async actions. Let's supose i have an action that makes an http call to an api to retrieve some info.

In that situation, should i inject the http client via action constructor? via dependency injection ? (get_it?)

The code i did works fine, but it's getting really hard to test it, and i'm sure it's my fault.

Can you give some light?

Thanks a lot

marcglasberg commented 4 years ago

Hi Rodrigo,

No, you should not inject the http-client via action constructor.

First of all, make sure you've read about the StoreTester: https://pub.dev/packages/async_redux#testing

Then, there are a few possibilities:

1) Use get_it or some other dependency injection code to inject the http client into the action reducer. This works well.

2) Use a DAO. For example:

   var someInfo = dao.readUserInfo(id);

Then you can mock the DAO itself, or inject the DAO via get_it. You can also make the dao a getter to some BaseAction (that extends ReduxAction) and inject it there.

Or else you keep the DAO as is, and mock or inject the http code in the DAO itself.

Note: If you inject the DAO into the action, then you are not testing the DAO itself. You are just unit testing the action. In this case, to be complete, you'll later have to test the DAO separately by injecting the http there. However, if you inject the http, then you are testing the action/DAO at the same time. It's not so "unit" anymore, a bit more like an integration test.

3) The readUserInfo method can be a local action method. For example:

   var someInfo = _readUserInfo(id);
   ...
   UserInfo _readUserInfo(String id) => dao.readUserInfo(id);

And then you can mock the action to override the _readUserInfo method (see the MockStore class).

rodrigobastosv commented 4 years ago

Thanks very much @marcglasberg , that was really helpfull.