001package org.unix4j.util; 002 003 004import java.io.File; 005import java.net.URL; 006 007public class FileTestUtils { 008 public static File getTestFile(Class<?> testClass, String fileName) { 009 final StackTraceElement stackTraceElement = StackTraceUtil.getCurrentMethodStackTraceElement(1); 010 return getTestFile(testClass, stackTraceElement.getMethodName(), fileName); 011 012 } 013 014 public static File getTestFile(Class<?> testClass, String testMethod, String fileName) { 015 return getTestFile(testClass, testMethod, fileName, null); 016 } 017 018 public static File getTestFile(Class<?> testClass, String testMethod, String fileName, String defaultFileName) { 019 return(getTestFile(getTestDir(testClass), testMethod, fileName, defaultFileName)); 020 } 021 022 public static File getTestFile(File parentDir, String testMethod, String fileName, String defaultFileName) { 023 File file = new File(parentDir, fileName); 024 if (!file.exists()) { 025 if (defaultFileName == null) { 026 throw new IllegalArgumentException("test file for " + parentDir.getName() + "." + testMethod + " not found, expected file: " + fileName); 027 } 028 file = new File(parentDir, defaultFileName); 029 if (!file.exists()) { 030 throw new IllegalArgumentException("test file for " + parentDir.getName() + "." + testMethod + " not found, expected file: " + fileName + " or default file: " + defaultFileName); 031 } 032 } 033 return file; 034 } 035 036 public static File getTestDir(Class<?> testClass){ 037 final String testDir = "/" + getTestDirRelativeToPackageDir(testClass); 038 URL fileURL = testClass.getResource(testDir); 039 if(fileURL == null){ 040 throw new IllegalArgumentException("Test directory does not exist. Please ensure it exists at [" + testDir + "]"); 041 } 042 return new File(fileURL.getFile()); 043 } 044 045 private static String getTestDirRelativeToPackageDir(Class<?> testClass) { 046 final String packageDir = testClass.getPackage().getName().replace('.', '-'); 047 return packageDir + "/" + testClass.getSimpleName(); 048 } 049}