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?

Spring bootでのログ出力のテスト

Last updated at Posted at 2024-12-27

以前に書いたログ出力のテストについての別解です。

ログ出力そのものが仕様になっている場合、ログに出力された内容に対してassertionを書きたいです。Spring Bootではそのための、JUnit5のExtensionを用意してあります。

使い方は上記のjavadocに書いてあるとおりですが、標準出力とやりとりするためのCapturedOutputが提供されているので、テストメソッドの引数などからそれを受け取れます。

java
@ExtendWith(OutputCaptureExtension.class)
class MyTest {

  @Test
  void testLog(CapturedOutput output) {
      // arrange
      ...

      // act
      service.apply(); // 中でログ出力している

      //assert
      assertThat(output).contains("done");
  }

}

test/resourceにlog4j2-test.xmlを配置すれば、テストコード実行時のloggerの設定ができます。

xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
	<Appenders>
		<Console name="CONSOLE" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n" />
		</Console>
	</Appenders>
	<Loggers>
		<Root level="info">
			<AppenderRef ref="CONSOLE" />
		</Root>
	</Loggers>
</Configuration>

このやり方だと、loggerをdependency injectionの形にしなくてもログ出力の内容をテストできます。

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?