11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

テストコードと依存するライブラリをjarにまとめてCLIで実行する

Posted at

タイトルのまんま。

テストだけ単体でCLIで実行できるようにしておけば、デプロイ用のchefのrun_listの中にレシピとして含めることができていろいろ捗ると思ったのでやってみた。

設定項目を全部理解して使ってるわけではないので、もっとうまい方法や設定があるのかもしれないけど、とりあえず取っ掛かりとして。

使ったmaven-pluginは、maven-assembly-plugin。依存関係をまとめてパッケージ化したい時に使うpluginで、java使いにとってこれ自体は珍しいものではないでしょう。普通は実行可能なjarを作成したりするときに使うのかな?今回はテスト実行用のjarをこれで作る。

pomはこんな感じ。

<build>
...
<plugins>
...
<plugin>
  <artifactId>maven-assembly-plugin</artifactId>
  <version>2.2</version>
  <executions>
    <execution>
      <id>make-assembly</id>
      <phase>package</phase>
      <goals>
        <goal>single</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <descriptors>
      <descriptor>src/test/resources/assembly.xml</descriptor>
    </descriptors>
  </configuration>
</plugin>
...

で、assembly.xmlは以下のとおり。

<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
  <id>test-jar-with-dependencies</id>
  <formats>
    <format>jar</format>
  </formats>
  <includeBaseDirectory>false</includeBaseDirectory>
  <dependencySets>
    <dependencySet>
      <outputDirectory>/</outputDirectory>
      <useProjectArtifact>true</useProjectArtifact>
      <unpack>true</unpack>
      <scope>test</scope>
    </dependencySet>
  </dependencySets>
</assembly>

mave-assembly-pluginには、元々jar-with-dependenciesという識別子であらかじめ定義されたアセンブリのルールがあるのだけど、それをベースに、<scope />を変えた。もともとは<scope>runtime</scope>で実行時に必要なもの、というルールなのだけど、そこを<scope>test</scope>に変えるとテスト実行時に、という設定に変わるようだ。

これでmvn installを実行すると、testコード、テスト用のライブラリ(UIテストなのでseleniumとかgebとかspockとか)が含まれたjarが出来上がる。拡張子jarをzipに変えて展開してみると確かに含まれているのがわかると思う。

上記方法で作成したテストコードを実行するには、先ほど作成したjarがあるフォルダで

java -cp 上で作ったjar org.junit.runner.JUnitCore テストが記載されたクラス名

もう少し具体的な例としては、

java -cp smoke-test-0.0.1-SNAPSHOT-test-jar-with-dependencies.jar org.junit.runner.JUnitCore sample.smoketest.SampleSpec

テストクラスを直指定しているところは改善の余地ありだけど、とりあえずこれでやりたいことはできそうな感じ。

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?