LoginSignup
1
1

More than 5 years have passed since last update.

spring bootのチュートリアルをとりあえずやってみる(2)

Last updated at Posted at 2018-03-16

spring bootのチュートリアルをとりあえずやってみる(1)の続きです。

今回もspring bootのチュートリアルの続きをやります。
今回は、前回書いたコードをunitテスト(単体テスト)します。

依存関係の追加

build.gradle
dependencies {
 // add
 testCompile("org.springframework.boot:spring-boot-starter-test")
}

テストの作成

(1)で作成したControllerに対してテストを作成します。

mkdir -p src/test/java/hello/
touch src/test/java/hello/HelloControllerTest.java

javaファイルの中身はチュートリアルからコピペ

HelloController.javaで定義したアクセス先(今回は"/")のステータスと戻り値をテストします。

HelloControllerTest.java
    .andExpect(status().isOk()) //ステータスがOKか?
    .andExpect(content().string(equalTo("Greetings from Spring Boot!"))); //戻る文字列がこれか?

テストの実施

実際テストを動かします。

// 成功ケース
./gradlew test
・・・色々出る
BUILD SUCCESSFUL in 1s //成功

// 失敗ケース 文字列を変えたりとかしてみる
./gradlew test
hello.HelloControllerTest > getHello FAILED
    java.lang.AssertionError at HelloControllerTest.java:29
2018-03-16 22:31:13.652  INFO 949 --- [       Thread-6] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@5da17b83: startup date [Fri Mar 16 22:31:10 JST 2018]; root of context hierarchy

1 test completed, 1 failed


FAILURE: Build failed with an exception.

以上で、unitテストもできそうです。
次回は、spring bootからJPAを用いてMySQLに接続してみようと思います。

1
1
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
1
1