2012年3月3日土曜日

Gradle + Groovy + Ideaをやってみよう

簡単なGradleのbuild.gradleファイルを作成してみた。

ビルドスクリプト


このbuildスクリプトはGoogle-guiceとh2データベースとjunitを入れるだけの簡単なプロジェクト。

def lang = ['java', 'groovy']
lang.each {ln ->
apply plugin: ln
}
apply plugin: 'idea'
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.inject:guice:3.0'
compile 'com.h2database:h2:1.3.156'
groovy 'org.codehaus.groovy:groovy:1.8.6'
testCompile 'junit:junit:4.10'
}
task structure(depends : idea) << {
def dirs = []
dirs << 'src'
sourceSets.all { src ->
dirs << "src/${src.name}"
lang.each { ln ->
dirs << "src/${src.name}/${ln}"
}
}
dirs.each {
def dir = new File(it)
if(dir.exists() == false) dir.mkdir()
}
}
view raw build.gradle hosted with ❤ by GitHub


読めば大体わかりますね。
javaとgroovyを使って、IntelliJ IDEAで開発できて、jarを最終的に吐き出すプロジェクトです。

GradleをMavenと比較して残念なところに、generate-archetypeみたいに、いい感じのディレクトリツリーを作ってくれるコマンドがないので、
とりあえず、ideaタスクの後に自作して強引に作るようにしています。


Tasks


Gradleでどのようなタスクがあるかを一覧表示します。

$ gradle tasks
:tasks
------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------
Build tasks
-----------
assemble - Assembles all Jar, War, Zip, and Tar archives.
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 the main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles the test classes.
Documentation tasks
-------------------
groovydoc - Generates Groovydoc API documentation for the main source code.
javadoc - Generates Javadoc API documentation for the main source code.
Help tasks
----------
dependencies - Displays the dependencies of root project 'gradle-study2'.
help - Displays a help message
projects - Displays the sub-projects of root project 'gradle-study2'.
properties - Displays the properties of root project 'gradle-study2'.
tasks - Displays the tasks runnable from root project 'gradle-study2' (some of the displayed tasks may belong to subprojects).
IDE tasks
---------
cleanIdea - Cleans IDEA project files (IML, IPR)
idea - Generates IDEA project files (IML, IPR, IWS)
Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.
Other tasks
-----------
cleanIdeaWorkspace
structure
Rules
-----
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.
Pattern: clean<TaskName>: Cleans the output files of a task.
To see all tasks and more detail, run with --all.
BUILD SUCCESSFUL
Total time: 4.78 secs
$


gradle tasksというコマンドがそれです。


プロジェクトの作成


では、ideaプロジェクトを作成しましょう。


$ REM before
$ dir
Volume in drive C is Windows7_OS
Volume Serial Number is 4ADF-A51E
Directory of C:\Users\mike\IdeaProjects\gradle-study2
2012/03/03 04:32 <DIR> .
2012/03/03 04:32 <DIR> ..
2012/03/03 04:32 <DIR> .gradle
2012/03/03 04:32 653 build.gradle
1 File(s) 653 bytes
3 Dir(s) 642,830,123,008 bytes free
$ rem EXECUTE
$ gradle idea
:ideaModule
Download http://repo1.maven.org/maven2/com/h2database/h2/1.3.156/h2-1.3.156.pom
Download http://repo1.maven.org/maven2/com/h2database/h2/1.3.156/h2-1.3.156-sources.jar
Download http://repo1.maven.org/maven2/com/h2database/h2/1.3.156/h2-1.3.156.jar
:ideaProject
:ideaWorkspace
:idea
BUILD SUCCESSFUL
Total time: 19.28 secs
$ dir
Volume in drive C is Windows7_OS
Volume Serial Number is 4ADF-A51E
Directory of C:\Users\mike\IdeaProjects\gradle-study2
2012/03/03 04:37 <DIR> .
2012/03/03 04:37 <DIR> ..
2012/03/03 04:32 <DIR> .gradle
2012/03/03 04:32 653 build.gradle
2012/03/03 04:37 7,182 gradle-study2.iml
2012/03/03 04:37 3,811 gradle-study2.ipr
2012/03/03 04:37 9,506 gradle-study2.iws
4 File(s) 21,152 bytes
3 Dir(s) 642,827,849,728 bytes free
$ gradle structure
:structure
BUILD SUCCESSFUL
Total time: 3.091 secs
$


gradle ideaコマンドとgradle structureコマンドを打つことでプロジェクトの構造が出来上がります。

実際にはideaタスクの後にstructureタスクを割りこませる方法があるんですが、忘れた…orz


プロジェクトの取り込み


では、作成したプロジェクトをideaで取り込みます。


Open Projectを選択します。

先程作成したgradle-study2.iprファイルを選択します。



こんな感じに依存性を解決したideaプロジェクトが作成されます。



GroovyでJUnit


JUnit4はPOJOまたはPOGOでできるので、GroovyでもJUnit4のテストを書けます。

では早速やってみましょう。

パッケージ作り忘れたので、src/test/groovyディレクトリで、[Alt + Insert]を押します。(MacではCtrl + n)




ここで「pa…」と入力すると、packageが選択できます。


適当にパッケージ名を入れましょう。



パッケージができたら、作成したパッケージのところでまたもや[Alt + Insert]。(MacではCtrl + n)

GroovyClassを選択します。



適当なので適当にクラス名を入れます。



早速、@Beforeから書いて行きましょう。



IDEAの素晴らしいところは、あの忌々しい[Ctrl + Space]を入れなくてもどんどん補完してくれる所




さらには依存性が解決している範囲で、あの忌々しい[Ctrl + 1]を入力しなくても、[Alt + Enter]で勝手にimport文を作ってくれるあたり。


なんか適当にlistとかいうフィールド、インスタンスを作ってみましたが、
これはフィールドとして設定しましょう。

listが初出の場所にカーソルを当てて、[Ctrl + Alt + f]、(Macの場合は[コマンド + alt + f])

でいい感じにフィールドを作成してくれます。



適度にスコープを選択して、defで割り当てましょう。


おもむろにテストを書いてみましょうか。

なんか、何もしていないのにアノテーションですら自動補完してくれます。



JUnit4をJavaでやるときはもちろん、org.junit.Assert.assertThatあたりを用いますが、
Groovyでテストをするときは、そんなもん使いません。

assertだけで十分です。


テストわざと間違えていますが…

テストを実行するのは、[alt + shift + F10]です。

何のテストを実行したいか選択して下さい。

メソッド単位で実行できます。



さて、実行結果です。
もちろんテスト間違えているので、どうなるか気になりますね。

テスト実行結果。



何がどういう値で、何が間違っているかがちゃんと表示されるんです。

これはGroovyだからできるんです。Power Assertと言います。

これはGroovyだからできるんです。Power Assertと言います。

大事な事ですから二度言いました。

これはGroovyだからできるんです。Power Assertと言います。


これがJUnitのassertThatなどだったら、expected<4> but got <3> くらいしか出してくれません。


この親切さ。これはGroovyだからできるんです。Power Assertと言います。


こいつはテストを直しておきます。



POJOのテスト


POJOもテストしましょう。もちろんテストはGroovyでやっちゃいます。


とりあえず、誰でも思いつきそうなPOJOでPersonというクラスを作ります。


メンバーはintのageとStringのfirstNameとlastNameです。

getterとsetter作らないとですね。


何もない所で、[alt + insert]を押します。(Mac版ちょっとど忘れ)



とりあえず、メンバー全部選択しましょう。



まあ、このあたりはeclipseでもやれるので、どうということはないですね。



じゃあ、テストを書きましょう。もちろんGroovyで。

Groovyでは特にコンストラクターが指定されていなければ、内部のフィールドに値を一気に代入させることができます。



ほんまかいな?と思うので、assertをかけてみましょう。




さ、テストを実行しましょう。


ほれ、ノープロブレム!!!!



Gradleに戻って


とりあえず、テストを落ちるようにしておきます。




では、gradleでテストを実行します。

テスト実行結果

$ gradle test
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:compileTestJava UP-TO-DATE
:compileTestGroovy
:processTestResources UP-TO-DATE
:testClasses
:test
Test org.mikeneck.gradle.guice.ListTest FAILED
Test org.mikeneck.gradle.guice.model.PersonTest FAILED
2 tests completed, 2 failures
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':test'.
> There were failing tests. See the report at C:\Users\mike\IdeaProjects\gradle-study2\build\reports\tests.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 10.554 secs



さて、テストが2つコケたらしいですね。

では結果をhtmlファイルで見てみます。

これがレポートファイルです。


これらの詳細を見ることができます。




ちゃんとテストがどういう点が悪くてfailしたのか一目瞭然ですね。

というわけで、Gradle、あの複雑なpomを書かなくても、いい感じで、ココまでやってくれるのですから、今はAnt + Ivyだけどという人は是非トライしてみましょう。


0 件のコメント:

コメントを投稿