Closed rslosarz closed 5 years ago
@rslosarz I would just like to understand how you are using the DI.
I would strongly advise that no service or component or anything is dependent on the injector. I would always ensure a service's dependencies are injected into that service rather than the service knowing about the injector and getting them itself. This will help to stop the scenario you have just encountered.
As a general rule if you are using the injector outside of initializing it you are doing something wrong.
Therefore, I would ensure the above service looks something like this.
class SomeRepository implements RepoInterface {
final SomeSourceInterface _source;
SomeRepository(this._source);
@override
List<Results> getResults() {
List<Results> list = _source.getObjects();
(...) //some data processing, repo pattern etc.
}
}
class InjectionInit {
// pass in an injector instance so you are not coupled to static methods
static void init(Injector injector) {
injector.map<SomeSourceInterface>((i) => new ProdImplementation());
injector.map<SomeRepository>((i) => new SomeRepository(i.get<SomeSourceInterface>()));
}
}
Then your test would look like this:
import 'package:flutter_simple_dependency_injection/injector.dart';
import 'package:test_api/test_api.dart';
import 'package:mockito/mockito.dart';
class MockImplementation extends Mock implements SomeSourceInterface {}
void main() {
group('SomeRepository tests', () {
SomeRepository repo;
MockImplementation source;
setUp(() {
source = new MockImplementation();
repo = new SomeRepository(source);
});
tearDown(() {
repo = null;
});
test('test', (){
when(source.getObjects()).thenReturn(...);
(...)
});
});
}
I hope this help. Let me know your thoughts.
@rslosarz did this approach help?
I'd suggest adding a map method for testing purposes, that will allow overriding existing objectKeys. This is quite useful while Unit Testing, where tested object uses some Injected implementation that we'd like to mock.
This is the method I'm thinking of:
This is the case I'm talking about: This is tested object:
This is class handling DI initialisation:
Normally used like this:
And this is Unit Test class where I'd like to mock SomeSourceInterface: