10

Spring Boot に基づくプロジェクトをいくつかの Maven モジュールに分割しました。これで、war-project だけがスターター クラス (メイン メソッドを持ち、Spring を開始する) を含み、他のモジュールは jar 型になります。

スターターが含まれていない場合、jar プロジェクトをテストするにはどうすればよいですか?

JUnit テスト ケース ヘッダーの例:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(StarterClassInDifferentProject.class)
...
4

3 に答える 3

6

同様の状況を解決しました。私は2つのモジュールを持つプロジェクトを持っています:

  1. ドメインとユーティリティクラスを含む「lib」プロジェクト、
  2. スプリング ブート アプリケーション、テンプレート、コントローラーなどを含む「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...
    }
于 2016-06-14T15:22:45.830 に答える