0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBootでのテストコードの簡単導入(UTの書き方の記憶を呼び覚ましたい人向け)

Last updated at Posted at 2022-12-13

前提

SpringBoot 2.7.6 準拠。

起動

テストクラスに @SpringBootTest を付ける。

サーバとして起動させてテストしたい時は、

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

上手く起動しない場合、classesでSpringBootの起動クラス(@SpringBootApplicationが付いてるクラス)を指定する。

@SpringBootTest(classes = TopazBackendApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)

実行

テスト実行

実行させたいメソッドには @Testを付ける。

SQL実行

SQLを実行したい場合、 @Sql("classpath:ファイル名") を付ける

モック化

@MockBean or @SpyBean

検索すると良く引っかかる↓は不要(SpringBootのverupで要らなくなってると思われる)
@InjectMocks, MockitoAnnotations.initMocks(this);

標準出力、エラーが欲しい場合

テストクラスに @ExtendWith(OutputCaptureExtension.class)
関数の引数に CapturedOutput output

モックされたインスタンスメソッドに渡された引数値を見たい場合

// モックの宣言
@MockBean
HogeService hogeService;

// ...略...

// 以下、テストコード内(String は HogeService#mockedMethod(String arg) の引数型)
final ArgumentCaptor<String> capture = ArgumentCaptor.forClass(String.class);
doNothing().when(hogeService).mockedMethod(capture.capture());

// 値の取得は
capture.getValue();

メモ

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?