Gradle初心者によるGradle事始め(ver6.5.1版)
初めに
本記事は、QiitaのGradle初心者によるGradle事始めの記事を、Gradleのバージョン6.5.1用に書き直したものになります。
主な変更点
- コマンドの出力結果
- taskの記載方法
- compileライブラリの非推奨化
Gradleとは
Gadleとは、Groovyで記述するビルド自動化システムです。 JAVAで古くから使われていたAntやMavenはXMLで記述するのに対し、 GradleはGroovyで記述できるため柔軟で協力なビルド自動化システムといえます。
「規約によるビルド」
MavenyたGradleは「規約によるビルド」システムと言われています。 一方、古くからあるmakeやAntは「手続き的なビルド」システムと言われています。
「手続き的なビルド」はソースファイルがあるディレクトリや生成ファイルの 出力先のディレクトリを逐次指定する必要がありましたが、「規約によるビルド」はシステム側に一定のルール(規約)があり、 ビルドシステムを利用する我々はそのルールに則ってソースファイルなど配置します。 ルールに則っていればスクリプトが簡潔だというのが、「規約によるビルド」を採用しているGradleの強みといえるでしょう。
Gradleのインストール
下記の手順でGradleのインストールと確認を行います。
必要な環境
現在のGradle最新版は6.5.1になります。
GradleはJVM言語なので、Javaの環境が必要で、6.5.1はJAVA 8〜14のJDKもしくはJREが必要です。
本手順を最後まで実行するためにはJDKをご準備ください。
手元のPCは「openjdk version "11.0.7"」なので、以下ではこの環境で試します。
ダウンロード
GradleのダウンロードサイトからComplete distributionもしくはBinary only distributionをダウンロードします。
Complete distributionにはドキュメント類も含まれているので、今回はComplete distributionをダウンロードします。
解凍と環境変数設定
ダウンロードしたZIPファイルを適当なディレクトリに解凍して、解凍したディレクトリまでをGRADLE_HOME
という環境変数に設定します。
併せてGRADLE_HOMEのbinディレクトリまでをPATH
環境変数に追加します。
インストール出来たかテストする
コンソールを立ち上げてgradle -version
を実行し、Gradleがインストールできたかテストします。
Welcome to Gradle 6.5.1! Here are the highlights of this release: - Experimental file-system watching - Improved version ordering - New samples For more details see https://docs.gradle.org/6.5.1/release-notes.html ------------------------------------------------------------ Gradle 6.5.1 ------------------------------------------------------------ Build time: 2020-06-30 06:32:47 UTC Revision: 66bc713f7169626a7f0134bf452abde51550ea0a Kotlin: 1.3.72 Groovy: 2.5.11 Ant: Apache Ant(TM) version 1.10.7 compiled on September 1 2019 JVM: 1.8.0_221 (Oracle Corporation 25.221-b11) OS: Windows 10 10.0 x86
このようにバージョン情報が表示されればOKです。
Gradleを入れると、一緒にGroovyとAntが入る用ですね。
プロキシ設定
仕事場でGradleを使う場合、プロキシサーバを設定しないと後々困るのでここで設定します。
今回はユーザごとにGradleの設定を施す。
~/.gradle/gradle.properties
ファイルにプロキシ設定を記述します。
systemProp.http.proxyHost=xxx.xxx.xxx.xxx systemProp.http.proxyPort=9999 systemProp.https.proxyHost=xxx.xxx.xxx.xxx systemProp.https.proxyPort=9999
Gradleのキホン
設定が完了したので、本題に入ります。
以下では適当なところにGradleSample
というディレクトリを作成し、その中で各種のコマンドを実行します。
Gradleの入口
GradleはPATH環境変数に設定したディレクトリにあるgradle
コマンドからすべての操作を実行します。
(すでにgradle -version
は実行しましたね)
手始めに引数無しのgradle
コマンドを実行してみましょう。
Starting a Gradle Daemon (subsequent builds will be faster) > Task :help Welcome to Gradle 6.5.1. To run a build, run gradle <task> ... To see a list of available tasks, run gradle tasks To see a list of command-line options, run gradle --help To see more detail about a task, run gradle help --task <task> For troubleshooting, visit https://help.gradle.org Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/6.5.1/userguide/command_line_interface.html#sec:command_line_warnings BUILD SUCCESSFUL in 7s 1 actionable task: 1 executed
引数無しのgradle
コマンドの簡単なヘルプが出力されます。
ビルドをしたければgradle <task>
を実行し、
利用可能なタスクを表示したければgradle tasks
を実行し、
コマンドラインオプションを表示したければgradle --help
を実行し、
それぞれのタスクについて詳細が知りたければgradle help --task <task>
を実行しろと言っています。
<task>
の部分には具体的なタスク名を記述します。
この「タスク」がGradleのキモとなる部分です。
次にこのタスクについてみてみます。
タスク
いまいるGradleSampleディレクトリにbuild.gradle
というファイル作って、テキストエディタで以下の内容を書き込みます。
task hello { doLast { println 'Hello world!' } }
見て迷うことはないでしょうが、そのスクリプトにいま「hello」というタスクがあり、そのタスクはHello world!
を出力します。
これをgradleコマンド実行します。
build.gradleはがデフォルトで読み込むビルドスクリプトですので、gradleコマンドにはスクリプトファイル名を指定する必要ありません。
また今回はログ出力を抑制して内容をスッキリさせるために-q
オプションをつけます。
実行するコマンドはgradle -q hello
です。
>gradle -q hello Hello world!
意図した結果が出力されました。
タスクには、ある処理のまとまりを記述できます。 このタスクを使って、「コンパイルをする」や「テストを実行する」など処理を行います。
タスクの依存関係
Gradleに限らず、ビルドシステムには「タスクの依存関係」は必要不可欠な概念です。
例えばテストを実行するためにはコンパイルが完了していなければなりません。
これは「テスト実行する」というタスクは「コンパイルをする」というタスクに依存している状態です。
この依存関係を、Gradleでは以下のとうに記述します。
task runCompile { doLast { println 'Run compile.' } } task executeTest(dependsOn: runCompile) { doLast { println 'Execute test.' } }
タスク名の後ろに(dependsOn: XXX)
を記述し、XXX
の部分に依存するタスク名を指定します。
このビルドスクリプトを実行します。
指定するタスクは「テストを実行する」ためgradle -q executeTest
です。
>gradle -q executeTest Run compile. Execute test.
executeTestを実行する前に、依存しているrunCompileを実行しているのが分かると思います。
タスクの一覧
Gradleはタスクを指定して実行することはわかっていただけたでしょうが、そのタスクはビルドスクリプトを開かなくてもgradle -q tasks
を実行すればわかります。
>gradle -q tasks ------------------------------------------------------------ Tasks runnable from root project ------------------------------------------------------------ Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files. Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleSample'. components - Displays the components produced by root project 'GradleSample'. [incubating] dependencies - Displays all dependencies declared in root project 'GradleSample'. dependencyInsight - Displays the insight into a specific dependency in root project 'GradleSample'. dependentComponents - Displays the dependent components of components in root project 'GradleSample'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'GradleSample'. [incubating] outgoingVariants - Displays the outgoing variants of root project 'GradleSample'. projects - Displays the sub-projects of root project 'GradleSample'. properties - Displays the properties of root project 'GradleSample'. tasks - Displays the tasks runnable from root project 'GradleSample'. To see all tasks and more detail, run gradle tasks --all To see more detail about a task, run gradle help --task <task>
今回作成したビルドスクリプトの内容が表示されました。
おや?でも、肝心の確認したいタスクのexecuteTest
とrunCompile
がありません。
今度はgradle -q tasks --all
を実行し、すべての情報を出力します。
>gradle -q tasks --all ------------------------------------------------------------ Tasks runnable from root project ------------------------------------------------------------ Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files. Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleSample'. components - Displays the components produced by root project 'GradleSample'. [incubating] dependencies - Displays all dependencies declared in root project 'GradleSample'. dependencyInsight - Displays the insight into a specific dependency in root project 'GradleSample'. dependentComponents - Displays the dependent components of components in root project 'GradleSample'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'GradleSample'. [incubating] outgoingVariants - Displays the outgoing variants of root project 'GradleSample'. projects - Displays the sub-projects of root project 'GradleSample'. properties - Displays the properties of root project 'GradleSample'. tasks - Displays the tasks runnable from root project 'GradleSample'. Other tasks ----------- executeTest prepareKotlinBuildScriptModel runCompile
Other tasks
のところにexecuteTest
とrunCompile
が表示されました。
これが「タスクの依存関係」を表しています。
他の依存関係の表現として行の最後の[XXXX]
があるのですが、これは後ほど説明しあmsう。
Gradleを使ったJavaのビルド
以下ではGradleを使ったJavaソースコードのビルド方法を記します。
先ほどまで使っていたbuild.gradle
は不要なので削除しましょう。
サンプルのプロジェクトを作成
Gradleはinit
タスクでJava/Groovy/Scalaの雛形プロジェクトを作成することができます。
gradle help --task init
を実行して、init
の使い方を調べます。
>gradle help --task init > Task :help Detailed task information for init Path :init Type InitBuild (org.gradle.buildinit.tasks.InitBuild) Options --dsl Set the build script DSL to be used in generated scripts. Available values are: groovy kotlin --package Set the package for source files. --project-name Set the project name. --test-framework Set the test framework to be used. Available values are: junit junit-jupiter kotlintest scalatest spock testng --type Set the type of project to generate. Available values are: basic cpp-application cpp-library groovy-application groovy-gradle-plugin groovy-library java-application java-gradle-plugin java-library kotlin-application kotlin-gradle-plugin kotlin-library pom scala-library swift-application swift-library Description Initializes a new Gradle build. Group Build Setup BUILD SUCCESSFUL in 2s 1 actionable task: 1 executed
今回はJavaのプロジェクトを作成したので、gardle init --type java-library
を実行します。
>gradle init --type java-library Select build script DSL: 1: Groovy 2: Kotlin Enter selection (default: Groovy) [1..2] Select test framework: 1: JUnit 4 2: TestNG 3: Spock 4: JUnit Jupiter Enter selection (default: JUnit 4) [1..4] Project name (default: GradleSample): Source package (default: GradleSample): > Task :init Get more help with your project: https://docs.gradle.org/6.5.1/userguide/java_library_plugin.html BUILD SUCCESSFUL in 12s 2 actionable tasks: 2 executed
言語やフレームワーク、プロジェクト名、ソースパッケージを選択できますが、今回は全てdefault
で実行します。
init
が完了すると、各種ファイルが生成されます。
│ .gitattributes │ .gitignore │ build.gradle │ gradlew │ gradlew.bat │ settings.gradle │ ├─.gradle │ ├─6.5.1 │ │ │ gc.properties │ │ │ │ │ ├─executionHistory │ │ │ executionHistory.bin │ │ │ executionHistory.lock │ │ │ │ │ ├─fileChanges │ │ │ last-build.bin │ │ │ │ │ ├─fileHashes │ │ │ fileHashes.bin │ │ │ fileHashes.lock │ │ │ │ │ └─vcsMetadata-1 │ ├─buildOutputCleanup │ │ buildOutputCleanup.lock │ │ cache.properties │ │ outputFiles.bin │ │ │ ├─checksums │ │ checksums.lock │ │ │ └─vcs-1 │ gc.properties │ ├─gradle │ └─wrapper │ gradle-wrapper.jar │ gradle-wrapper.properties │ └─src ├─main │ ├─java │ │ └─GradleSample │ │ Library.java │ │ │ └─resources └─test ├─java │ └─GradleSample │ LibraryTest.java │ └─resources
色々なディレクトリやファイルが作成されますが、重要なのはbuild.gradle
ファイルと、src
ディレクトリです。
(他のディレクトリとファイルは今回説明を省力します)
ビルドスクリプトの確認
作成されたbuild.gradle
ファイルを見てみます。
/* * This file was generated by the Gradle 'init' task. * * This generated file contains a sample Java Library project to get you started. * For more details take a look at the Java Libraries chapter in the Gradle * User Manual available at https://docs.gradle.org/6.5.1/userguide/java_library_plugin.html */ plugins { // Apply the java-library plugin to add support for Java Library id 'java-library' } repositories { // Use jcenter for resolving dependencies. // You can declare any Maven/Ivy/file repository here. jcenter() } dependencies { // This dependency is exported to consumers, that is to say found on their compile classpath. api 'org.apache.commons:commons-math3:3.6.1' // This dependency is used internally, and not exposed to consumers on their own compile classpath. implementation 'com.google.guava:guava:29.0-jre' // Use JUnit test framework testImplementation 'junit:junit:4.13' }
コメントが多いので今回はコメントを削除します。
plugins { id 'java-library' } repositories { jcenter() } dependencies { api 'org.apache.commons:commons-math3:3.6.1' implementation 'com.google.guava:guava:29.0-jre' testImplementation 'junit:junit:4.13' }
スッキリしました。
Javaプラグイン
plugins { id 'java-library' }
で、これを記述するとJavaのビルドに必要な各種タスクが読み込まれます。
他にも、.projectのようなEclipse固有の設定ファイルを生成するプラグインや、Groovyや、 Scalaなどもありますが、今回は省略します。
plugins { id 'eclipse' }
Groovy
plugins { id 'groovy' }
plugins { id 'scala' }
詳細は、Gradleの公式ユーザーガイドを参照してください。
リポジトリの指定
Javaのプログラムを書く上で、Sprong BootやJUnitやSLF4Jなどのライブラリを使用しないことはないでしょう。
Antの時代は各ライブラリの提供元のサイトから必要なJARファイルをダウンロードしてコンパイル時にローカルのパスを指定していましたが、Mavenの時代からそれはセントラルリポジトリと呼ばれるリモートに置かれ、必要に応じてビルドシステムが自動的にダウンロードするようになりました。
MavenであればMaven Central Repositoryからダウンロードします。
GradleはGadle固有のセントラルリポジトリがあるわけではなく、Mavenなど既存のセントラルリポジトリからライブラリをダウンロードします。
どのセントラルリポジトリを使用するかは、ビルドスクリプトの下記で指定します。
repositories { jcenter() }
これは「BintrayのJCenterにある依存関係を探すための定義済みリポジトリ」を意味します。
今回は、Mavenセントラルリポジトリを参照したいので、これを以下のように変更します。
repositories { mavenCentral() }
依存関係の定義
リポジトリからどのライブラリを使用するのかを定義するのが、ビルドスクリプトの下記の部分です。
dependencies { api 'org.apache.commons:commons-math3:3.6.1' implementation 'com.google.guava:guava:29.0-jre' testImplementation 'junit:junit:4.13' }
ここで言う「依存関係」はライブラリの「依存関係」です。
タスクの依存関係ではありません。
api
は、特に意図せずとも他のプロジェクトに依存関係を伝番させるライブラリ(compile
と同じ様な認識)です。
implementation
は、明示しない限り他のプロジェクトに依存関係を伝番させないライブラリです。テスト時とコンパイル時に使用します。
testImplementation
で指定するのはテスト時に使用するライブラリです。
詳しく知りたい方は、Gradle の compile, api, implementation とかについてを参照してください。
ライブラリの指定は、コロン区切りで'GroupId : ArtifactId : Version'
の3つが必要です。
この3つはMavenセントラルリポジトリにあるものを指定します。
タスクの確認
この状態でタスクの一覧を確認します。
>gradle tasks --all Starting a Gradle Daemon (subsequent builds will be faster) > Task :tasks ------------------------------------------------------------ Tasks runnable from root project ------------------------------------------------------------ Build tasks ----------- assemble - Assembles the outputs of this project. build - Assembles and tests this project. buildDependents - Assembles and tests this project and all projects that depend on it. buildNeeded - Assembles and tests this project and all projects it depends on. classes - Assembles main classes. clean - Deletes the build directory. jar - Assembles a jar archive containing the main classes. testClasses - Assembles test classes. Build Setup tasks ----------------- init - Initializes a new Gradle build. wrapper - Generates Gradle wrapper files. Documentation tasks ------------------- javadoc - Generates Javadoc API documentation for the main source code. Help tasks ---------- buildEnvironment - Displays all buildscript dependencies declared in root project 'GradleSample'. components - Displays the components produced by root project 'GradleSample'. [incubating] dependencies - Displays all dependencies declared in root project 'GradleSample'. dependencyInsight - Displays the insight into a specific dependency in root project 'GradleSample'. dependentComponents - Displays the dependent components of components in root project 'GradleSample'. [incubating] help - Displays a help message. model - Displays the configuration model of root project 'GradleSample'. [incubating] outgoingVariants - Displays the outgoing variants of root project 'GradleSample'. projects - Displays the sub-projects of root project 'GradleSample'. properties - Displays the properties of root project 'GradleSample'. tasks - Displays the tasks runnable from root project 'GradleSample'. Verification tasks ------------------ check - Runs all checks. test - Runs the unit tests. Other tasks ----------- compileJava - Compiles main Java source. compileTestJava - Compiles test Java source. prepareKotlinBuildScriptModel processResources - Processes main resources. processTestResources - Processes test resources. Rules ----- Pattern: clean<TaskName>: Cleans the output files of a task. Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration. Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration. BUILD SUCCESSFUL in 8s 1 actionable task: 1 executed
Java用のプラグインを指定しているので、Build tasks
などが追加されています。
ビルドする場合、build
タスク指定します。
ここで先ほど保留した依存するタスクの話をします。
build
タスクの右にある[assemble, check]
となっている部分が依存しているタスクです。
build
タスクの前にassemble
タスク(プロジェクトのすべてのアーカイブを構築)とcheck
タスク(プロジェクトのすべての検証タスクを実行)が実行されます。
assemble
タスクの前にはjar
タスク(当該プロジェクトのJARファイルを構築)が実行され、
jar
タスクの前にはclasses
タスク(製品クラスディレクトリを構築)が実行され、
classes
タスクの前にはcompileJava
タスク(javacを使って製品javaソースファイルをコンパイル)とprocessResources
タスク(製品リソースを製品クラスディレクトリにコピー)が実行されます。
規約
Gradleは「規約によるビルド」をするビルドシステムだと言いましたが、Javaプラグインを使用する場合は下記のようなディレクトリの規約があります。
ディレクトリ | 意味 |
---|---|
src/main/java | 製品のJavaリソース |
src/main/resources | 製品のリソース |
src/test/java | テストのJavaリソース |
src/test/java | テストのリソース |
ここでもう一度init
タスクで作成したディレクトリを見てみます。
└─src ├─main │ ├─java │ │ └─GradleSample │ │ Library.java │ │ │ └─resources └─test ├─java │ └─GradleSample │ LibraryTest.java │ └─resources
init
タスクで作成された「製品のJavaソース」ディレクトリと「テストのJavaソース」ディレクトリが、規約に則ったディレクトリだということが分かってもらえるかと思います。
ビルドの実行
処理を確認するために、ログレベルをinfoに変更するオプション-i
をつけてgradle build -i
で実行しましょう。
>gradle build -i -- 略 -- > Configure project : Evaluating root project 'GradleSample' using build file 'C:\Users\testuser\Desktop\test\GradleSample\build.gradle'. All projects evaluated. Selected primary task 'build' from project : Tasks to be executed: [task ':compileJava', task ':processResources', task ':classes', task ':jar', task ':assemble', task ':compileTestJava', task ':processTestResources', task ':testClasses', task ':test', task ':check', task ':build'] Tasks that were excluded: [] :compileJava (Thread[Execution worker for ':',5,main]) started. > Task :compileJava Caching disabled for task ':compileJava' because: Build cache is disabled Task ':compileJava' is not up-to-date because: Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\main has been removed. Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\main\GradleSample has been removed. Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\main\GradleSample\Library.class has been removed. The input changes require a full rebuild for incremental task ':compileJava'. Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments. Compiling with JDK Java compiler API. Created classpath snapshot for incremental compilation in 0.001 secs. :compileJava (Thread[Execution worker for ':',5,main]) completed. Took 0.138 secs. :processResources (Thread[Execution worker for ':',5,main]) started. > Task :processResources NO-SOURCE Skipping task ':processResources' as it has no source files and no previous output files. :processResources (Thread[Execution worker for ':',5,main]) completed. Took 0.001 secs. :classes (Thread[Execution worker for ':',5,main]) started. > Task :classes Skipping task ':classes' as it has no actions. :classes (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :jar (Thread[Execution worker for ':',5,main]) started. > Task :jar Caching disabled for task ':jar' because: Build cache is disabled Task ':jar' is not up-to-date because: Output property 'archiveFile' file C:\Users\testuser\Desktop\test\GradleSample\build\libs\GradleSample.jar has been removed. file or directory 'C:\Users\testuser\Desktop\test\GradleSample\build\resources\main', not found :jar (Thread[Execution worker for ':',5,main]) completed. Took 0.015 secs. :assemble (Thread[Execution worker for ':',5,main]) started. > Task :assemble Skipping task ':assemble' as it has no actions. :assemble (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :compileTestJava (Thread[Execution worker for ':',5,main]) started. > Task :compileTestJava Caching disabled for task ':compileTestJava' because: Build cache is disabled Task ':compileTestJava' is not up-to-date because: Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\test has been removed. Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\test\GradleSample has been removed. Output property 'destinationDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\classes\java\test\GradleSample\LibraryTest.class has been removed. The input changes require a full rebuild for incremental task ':compileTestJava'. Full recompilation is required because no incremental change information is available. This is usually caused by clean builds or changing compiler arguments. Compiling with JDK Java compiler API. Created classpath snapshot for incremental compilation in 0.002 secs. :compileTestJava (Thread[Execution worker for ':',5,main]) completed. Took 0.153 secs. :processTestResources (Thread[Execution worker for ':',5,main]) started. > Task :processTestResources NO-SOURCE Skipping task ':processTestResources' as it has no source files and no previous output files. :processTestResources (Thread[Execution worker for ':',5,main]) completed. Took 0.001 secs. :testClasses (Thread[Execution worker for ':',5,main]) started. > Task :testClasses Skipping task ':testClasses' as it has no actions. :testClasses (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :test (Thread[Execution worker for ':',5,main]) started. Gradle Test Executor 2 started executing tests. Gradle Test Executor 2 finished executing tests. > Task :test Caching disabled for task ':test' because: Build cache is disabled Task ':test' is not up-to-date because: Output property 'binaryResultsDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\test-results\test\binary has been removed. Output property 'binaryResultsDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\test-results\test\binary\output.bin has been removed. Output property 'binaryResultsDirectory' file C:\Users\testuser\Desktop\test\GradleSample\build\test-results\test\binary\output.bin.idx has been removed. Starting process 'Gradle Test Executor 2'. Working directory: C:\Users\testuser\Desktop\test\GradleSample Command: C:\Program Files\AdoptOpenJDK\jdk-11.0.7.10-hotspot\bin\java.exe -Dorg.gradle.native=false @C:\Users\testuser\AppData\Local\Temp\gradle-worker-classpath3706733076989153461txt -Xmx512m -Dfile.encoding=windows-31j -Duser.country=JP -Duser.language=ja -Duser.variant -ea worker.org.gradle.process.internal.worker.GradleWorkerMain 'Gradle Test Executor 2' Successfully started process 'Gradle Test Executor 2' Finished generating test XML results (0.001 secs) into: C:\Users\testuser\Desktop\test\GradleSample\build\test-results\test Generating HTML test report... Finished generating test html results (0.008 secs) into: C:\Users\testuser\Desktop\test\GradleSample\build\reports\tests\test :test (Thread[Execution worker for ':',5,main]) completed. Took 1.395 secs. :check (Thread[Execution worker for ':',5,main]) started. > Task :check Skipping task ':check' as it has no actions. :check (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. :build (Thread[Execution worker for ':',5,main]) started. > Task :build Skipping task ':build' as it has no actions. :build (Thread[Execution worker for ':',5,main]) completed. Took 0.0 secs. BUILD SUCCESSFUL in 3s 4 actionable tasks: 4 executed
実行したタスクが列挙されています。
compileJava
から、build
まで実行されました。
最初は依存ライブラリのダウンロードが発生するかもしれません。
もしプロキシを使用する環境で実行した場合、設定の不備があるとダウンロードに失敗するはずなので、設定を見直してください。
ビルド時に生成されるファイルはbuild
ディレクトリにあります。
今回のテンプレートソースのJARファイルはbuild/libs/GradleSample.jar
です。
実行したタスクにtest
があるのでテストは実行されたはずですが、念のためにテストクラスでエラーを起こしてみます。
src/test/java/GradleSample/LibraryTest.java
を修正します。
修正前は下記のソースでした。
package GradleSample; import org.junit.Test; import static org.junit.Assert.*; public class LibraryTest { @Test public void testSomeLibraryMethod() { Library classUnderTest = new Library(); assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod()); } }
これにエラーとなる処理を入れます。
package GradleSample; import org.junit.Test; import static org.junit.Assert.*; public class LibraryTest { @Test public void testSomeLibraryMethod() { Library classUnderTest = new Library(); assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod()); assertTrue(false); } }
assertTrue(false);
でテストは失敗するはず。
gradle build -i
を実行します。
>gradle build > Task :test FAILED GradleSample.LibraryTest > testSomeLibraryMethod FAILED java.lang.AssertionError at LibraryTest.java:14 1 test completed, 1 failed FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':test'. > There were failing tests. See the report at: file:///C:/Users/testuser/Desktop/test/GradleSample/build/reports/tests/test/index.html * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights. * Get more help at https://help.gradle.org BUILD FAILED in 3s 4 actionable tasks: 1 executed, 3 up-to-date
テストが失敗しました。
なのでここまで最初に言った「JavaのソースコードをコンパイルしてJARファイルにまとめてテストを実行するまで」が達成しました。
終わりに
私は、開発の知識がまるで無い状態で開発の自動化(CICD)の業務を担当することになりました。
Gradleの開発自動化といわれても、Gradleって何?という状態だった私はパニックでした。
Gradleについて何から勉強してよいかわからない状態だったのですが、そんな時に上記の記事を見かけて学習の取っ掛かりにできました。
以上です。