🐷

Spring Boot アプリケーションを Junit でテストする

に公開

Spring Boot | Junit

テストクラス

  • testディレクトリへ、テストクラスを書いていく。
  • テストクラスのクラス名は、"テストするクラス名+Test"にするとよい。
    ⇒ Mavenの仕様ではある特定の命名パターンに従っていないと、クラスはテストクラスとして認識されずテストが実行されない。Mavenはデフォルトで、下記に示す特定のクラス名をテストクラスとして認識する。
Mavenはデフォルトで、下記に示す特定のクラス名をテストクラスとして認識する
*/Test.java
**/*Test.java
**/*Tests.java
**/*TestCase.java

テスト用プロパティファイル

  • テスト用にプロパティファイルの値を変更したい場合、テストのリソースディレクトリ (test/resources) 下に本番コード用のプロパティファイルと同じ名前のファイルを配置する。
  • import org.junit.jupiter.api.Test;をインポートする。

EclipseでのJunit動作例

  • テストの結果はPASSの際は緑色で、NGの際は赤色で分かりやすく表示される。

[Eclipseでの動作例]

/* Junitテストコード Spring Boot サンプル例 */
package com.example.samuraitravel;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AdminHouseControllerTest {
	
	@Autowired
	private MockMvc junitTest;
	
	@Test
	public void testMethod1() throws Exception{
		
		junitTest.perform(get("/admin/houses"))
            //レスポンスステータスコードが 3xx の範囲であることをアサートします。
			.andExpect(status().is3xxRedirection())
			.andExpect(redirectedUrl("http://localhost/no-url"));
		
		
	}

}
  • TEST PASS
    SpringBoot_Junit_Sample_pass

  • TEST NG
    SpringBoot_Junit_Sample_ng

結合テスト with Selenium

Cucumber, Turnip | 振る舞い駆動開発(BDD)

Discussion