org.junit.jupiter.api.Test 패키지는 JUnit 5 를 사용하며 해당 어노테이션을 쓰지 않아도 동작하지만 org.junit.Test 패키지는 JUnit 4 를 사용하며 @RunWith(SpringRunner.class) 가 필수이다.
사이드 프로젝트 중 @Test 어노테이션 만으로도 동작하는 것을 확인하고 새로운 테스트 클래스를 만든 후에 스프링 빈이 주입되지 않아 당황하였다. 스프링 버젼 자체를 최신으로 해서 RunWith 어노테이션이 필요하지 않아진줄 알았지만 Test 어노테이션의 패키지가 영향을 준다는 사실을 확인했다.
코딩테스트의 대표 사이트인 백준과 프로그래머스의 문제에는 형식에 차이가 있다. 백준의 경우 테스트로 입력되는 파라미터가 System.in으로 입력되고, 정답의 경우 출력을 통하여 문제를 푼다면. 프로그래머스의 경우에는 solution 함수를 만들고, 해당 solution 함수의 파라미터로 테스트 케이스가 입력되고, 정답의 경우 return 값으로 처리 된다.
첫 줄에 남겨둔 링크인 이전 코드의 경우 백준을 고려하여 만들다보니 프로그래머스의 문제풀이 테스트 결과를 확인할 수 없는 문제가 있었다. 프로그래머스의 테스트 케이스를 문자열로 하여 적절하게 타입 변환 해주는 코드들을 작성할 수도 있었겠지만 Jackson 라이브러리 등을 붙이는 것이 아니면 과한 작업 소요라고 생각하였고, HashMap을 통하여 테스트 케이스 및 결과 케이스를 저장하는 형태로 테스트 환경을 구축하였다.
또한 실제 사이트에 제출 전 IDE에서 작성한 부분을 수정하는 작업을 최대한 적게 줄일 수 있도록 코드를 작성하였다.
백준과 프로그래머스의 두 케이스로 나누기 위해 전략패턴을 사용하고자 하였고, 우선 한 일은 문제에 대한 Interface 화이다.
백준과 프로그래머스에서 달라지는 케이스인 InputCase 와 ResultCase 를 구현 체에서 작성하게 하였고 test() 자체는 동일하게 구성하였다. 틀렸을 경우 확인하기 쉽도록 GPT의 도움을 받아 console 창에 색상과, 소리가 나는 코드를 추가하였다. 또한 케이스를 프린트 해볼 경우 Array 안의 다른 Object 가 있는 경우가 있어 print 관련하여서도 메서드를 추가하였다. 프로그래머스의 경우 input 과 return 의 타입이 변경될 수 있어서 제네릭을 이용하였다.
아래는 BaekJoon과 Programmers에서 Interface 메서드들을 구현한 내용들이다.
class BaekJoon
import java.io.*;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
public class BaekJoon implements Problem<File, String>{
Object answer;
File[] testFiles;
public Problem<File, String> setAnswer(Object answer) {
this.answer = answer;
URL classDir = answer.getClass().getResource("");
try{
testFiles = new File(classDir.toURI()).listFiles();
}catch (Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
return this;
}
@Override
public HashMap<String, File> getInputCase() {
HashMap<String, File> testCase = new HashMap<>();
Arrays.stream(testFiles)
.filter((file) -> file.getName().startsWith("input"))
.forEach(file -> {
String fileName = file.getName();
String testSeq = fileName.substring(fileName.indexOf("input") + "input".length(), fileName.lastIndexOf("."));
testCase.put(testSeq, file);
});
return testCase;
}
@Override
public HashMap<String, String> getResultCase() {
HashMap<String, String> result = new HashMap<>();
try {
Arrays.stream(testFiles)
.filter((file) -> file.getName().startsWith("result"))
.forEach(file -> {
String fileName = file.getName();
String testSeq = fileName.substring(fileName.indexOf("result") + "result".length(), fileName.lastIndexOf("."));
StringBuilder resultSb = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = "";
while ((line = br.readLine()) != null) {
resultSb.append(line).append(System.lineSeparator());
}
result.put(testSeq, resultSb.toString().trim());
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
return result;
}
@Override
public String solve(File file) throws Exception {
InputStream parameter = new FileInputStream(file);
System.setIn(parameter);
ByteArrayOutputStream resultOutputStream = new ByteArrayOutputStream();
PrintStream resultSave = new PrintStream(resultOutputStream);
PrintStream resultConsole = System.out;
System.setOut(resultSave);
// Solution class 변수 초기화를 위해 solve 마다 새로운 instance 생성
Constructor constructor = answer.getClass().getConstructor();
Object instance = constructor.newInstance();
instance.getClass()
.getDeclaredMethod("main", String[].class)
.invoke(instance, (Object) null);
System.out.flush();
String testResult = resultOutputStream.toString().trim(); // System.out.println() 으로 정답 입력시 개행문자 제거
resultOutputStream.close();
parameter.close();
System.setOut(resultConsole);
return testResult;
}
}