Refactor EngineService to be able to inject custom Engine

fixes #38
This commit is contained in:
Marty Oehme 2018-08-27 19:33:17 +02:00
parent dd18fc3bc7
commit 5e8f83cf8a
2 changed files with 30 additions and 9 deletions

View file

@ -5,10 +5,10 @@ import 'package:rules_of_living/src/Engine.dart';
class EngineService { class EngineService {
Engine _engine; Engine _engine;
Engine get engine => _engine ?? createEngine(null); Engine get engine => _engine ?? getEngine(Engine());
Engine createEngine(html.CanvasElement canvas) { Engine getEngine(Engine engine) {
_engine = Engine(canvas); _engine = engine;
return _engine; return _engine;
} }
@ -45,5 +45,4 @@ class EngineService {
} }
bool get isRunning => engine.running; bool get isRunning => engine.running;
} }

View file

@ -1,19 +1,41 @@
@TestOn('browser') @TestOn('browser')
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:mockito/mockito.dart';
import 'package:rules_of_living/src/Engine.dart';
import 'package:rules_of_living/service/engine_service.dart'; import 'package:rules_of_living/service/engine_service.dart';
class MockEngine extends Mock implements Engine {}
void main() { void main() {
EngineService sut; EngineService sut;
MockEngine me;
setUp(() { setUp(() {
me = MockEngine();
sut = EngineService(); sut = EngineService();
}); });
group("Dependency Injection", () {
test("EngineService accesses the Engine defined in getEngine", () {
sut.getEngine(me);
test("EngineService creates an engine on demand", () { Engine result = sut.engine;
expect(sut.engine, isNotNull); expect(result, equals(me));
});
}); });
group("caching", () {
test("EngineService creates an engine on demand", () {
Engine result = sut.engine;
expect(result, TypeMatcher<Engine>());
});
test("EngineService returns the cached engine on subsequent requests", () { test("EngineService returns the cached engine on subsequent requests", () {
expect(sut.engine, allOf(isNotNull, equals(sut.engine))); Engine result = sut.engine;
expect(sut.engine, equals(result));
});
test("caching can be overriden by providing a custom engine", () {
Engine first = sut.engine;
sut.getEngine(me);
Engine second = sut.engine;
expect(second, isNot(equals(first)));
});
}); });
} }