サービス依存関係を注入してJUnitテストを作成しようとしています。Guice注入によるRatpackサーバーのJUnitテスト
protected MainClassApplicationUnderTest aut = new MainClassApplicationUnderTest(App.class) {
@Override
protected void addImpositions(final ImpositionsSpec impositions) {
impositions.add(UserRegistryImposition.of(appRegistry -> {
// Allow modifying Injector in tests
return appRegistry.join(Guice.registry(injector));
}));
}
};
private Injector injector = com.google.inject.Guice.createInjector(new Module());
@Before
public void setup() {
injector.injectMembers(this);
}
@After
public void tearDown() {
aut.close();
}
、その後、私のテストクラスに注入されたサービスを使用して:私はHikariModule
で私のアプリに永続性を追加し始めるまで
@Inject
private UserService userService;
これは罰金働いていました。今、Guiceのレジストリの作成は、もう少し複雑です:
.join(Guice.registry(b -> b
.module(HikariModule.class, hikariConfig -> {
final String dbUrl = System.getenv("JDBC_DATABASE_URL");
hikariConfig.setJdbcUrl(dbUrl);
})
.module(Module.class)
.bind(DbMigrator.class)
).apply(r))
私は注射がテストに失敗したHikariModule
Guiceのから来るDataSource
クラスに依存したサービスを持っている場合は、私のレジストリは今、複数のモジュールから構成されているので。
私の目標は、以下の方法で書き込みテストをできるようにすることです:
@Inject // <- not required can be done in @Before method
private UserService userService; // <- Inject it somehow from Application under test
@Test
public void testUser() {
final Result<User, String> userResult = userService.create(new User.Registration());
final ReceivedResponse res = aut.getHttpClient().get("https://stackoverflow.com/users/" + user.userId);
assertEquals(200, res.getStatusCode());
}
テストでサービスの依存関係を注入する適切なアプローチは何ですか?私は非常に多くのguiceモジュールをMainClassApplicationUnderTest
から再利用するのではなく、自分自身を作成して上書きすることを好むでしょう。