同様の状況を解決しました。私は2つのモジュールを持つプロジェクトを持っています:
- ドメインとユーティリティクラスを含む「lib」プロジェクト、
- スプリング ブート アプリケーション、テンプレート、コントローラーなどを含む「Web」プロジェクト...
そして、「lib」プロジェクトをスプリングブートテストの方法でテストしたかったのです。
最初に、pom.xml にスコープ "test" で必要な依存関係を含めます (私の場合、H2 データベースもあります)。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.3.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- add also add this here, even if in my project it is already present as a regular dependency -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.3.3.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.191</version>
<scope>test</scope>
</dependency>
テスト目的で、「lib」プロジェクトのテスト ソースの中に、テスト構成として機能するクラスがあります。
package my.pack.utils;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@TestConfiguration
@EnableJpaRepositories(basePackages = {"my.pack.engine.storage", "my.pack.storage"})
@EntityScan(basePackages = {"my.pack.storage", "my.pack.entity"})
@EnableAutoConfiguration
public class MyTestConfiguration
{
}
これにより、アプリケーションのデータ アクセス機能をテストするために H2 データベースがセットアップされます。
最後に、役に立つと思われるテスト クラスでのみ、テスト構成を使用するように実行を構成します (必ずしもそうする必要はありませんが、便利な場合もあります)。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyTestConfiguration.class)
public class TestAClassThatNeedsSpringRepositories
{
// tests...
}