JUnitを使って、以下のような処理をテストメソッド単位で行うことは可能です。
各テストメソッドの実行前にログファイルを削除
これは、@Before
アノテーションを使うことで実現できます。このアノテーションを付けたメソッドは、各テストメソッドの実行前に呼び出されます。
各テストメソッドの実行後にフォルダを作成し、ログをそのフォルダに移動
これは、@After
アノテーションを使うことで実現できます。このアノテーションを付けたメソッドは、各テストメソッドの実行後に呼び出されます。
JUnit4 実装例
以下はその処理を実現する例です:
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class LogHandlingTest {
private static final String LOG_FILE = "test.log";
@Before
public void deleteLogBeforeTest() throws IOException {
Path logPath = Path.of(LOG_FILE);
if (Files.exists(logPath)) {
Files.delete(logPath);
System.out.println("ログ削除: " + LOG_FILE);
}
}
@After
public void createFolderAndMoveLogAfterTest() throws IOException {
String methodName = Thread.currentThread().getStackTrace()[2].getMethodName();
Path folderPath = Path.of("logs/" + methodName);
Files.createDirectories(folderPath);
Path logPath = Path.of(LOG_FILE);
if (Files.exists(logPath)) {
Path destination = folderPath.resolve(LOG_FILE);
Files.move(logPath, destination);
System.out.println("ログ移動: " + destination);
}
}
@Test
public void testMethod1() throws IOException {
// ダミーのログファイルを生成
Files.writeString(Path.of(LOG_FILE), "This is a log for testMethod1");
System.out.println("テストメソッド1 実行");
}
@Test
public void testMethod2() throws IOException {
// ダミーのログファイルを生成
Files.writeString(Path.of(LOG_FILE), "This is a log for testMethod2");
System.out.println("テストメソッド2 実行");
}
}
説明
deleteLogBeforeTest:
各テストの実行前に、指定されたログファイル (test.log) を削除します。
createFolderAndMoveLogAfterTest:
テストメソッド名に基づいたフォルダを作成し、そのフォルダにログファイルを移動します。
テストメソッド (testMethod1 など):
各テストメソッドで、ダミーログを作成しています。
実行結果例
テストを実行すると、以下のようなディレクトリ構成が生成されます:
logs/
└── testMethod1/
└── test.log
└── testMethod2/
└── test.log