2015年12月2日水曜日

samepropertyvaluesas で 「java.lang.NoSuchFieldError: NONE」

【エラー】
java.lang.NoSuchFieldError: NONE

【概要】
hamcrestのsamepropertyvaluesas を使用すると「java.lang.NoSuchFieldError: NONE」というエラーが出力されてテストが失敗する。


【原因】
junitライブラリに含まれているhamcrestクラスと、ダウンロードしたhamcrestライブラリに含まれるクラスがは競合いる。その為(おそらく)samepropertyvaluesasが呼び出しているクラスMatcher関連?が本来呼び出すべきバージョンと違うものになっていた為エラーが発生していた。
pom.xmlのjunitに関する定義ははnetbeansで自動生成されたものを使っていたが、それだとjunitライブラリにhamcrestのクラスが一部含まれてしまう為、除外する必要がある。
もしくは、依存関係の優先度をhamcrestライブラリ⇒junitの順にすればよいはず。


【対応】
pomを以下のように修正する。

案1 junit関連より先にhamcrestの依存性を定義する。

<dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>java-hamcrest</artifactId>
            <version>2.0.0.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <!-- org.hamcrestより上にしないこと!! -->
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.1</version>
            <scope>test</scope>
        </dependency>


案2 hamcrestが含まれないjunitライブラリを使用する。※junitのartifactIDをjunit-depにする
<dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>java-hamcrest</artifactId>
            <version>2.0.0.0</version>
            <scope>test</scope>
        </dependency>
<!--        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.1</version>
            <scope>test</scope>
        </dependency>
-->
        <dependency>
            <groupId>junit</groupId>
        <!-- artifactIDがjunit-dep -->
            <artifactId>junit-dep</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

どっちもうまくいったけど、まあ案1の方が、junit単独で使いたい時に簡単に戻せるので楽かな。



【残課題】
案1の場合、ふっと気を抜いてタグの順番を入れ替えたりしないようにしないといけない。
(忘れないようにコメントを追加しておく)

0 件のコメント:

コメントを投稿