/**
* JUnit用SecuriyManager
* System.Exitが呼ばれた際に、ExitExceptionにステータスを設定し、スローする。
*/
public Class TestSecurityManager extends SecuriyManager {
public TestSecurityManager() {}
@override
public void checkPermission(Permission permission) {
}
@override
public void checkExit(int status) {
throw new ExitException(status);
}
}
/**
* System.Exitが呼ばれた際にスローする例外
*/
public class ExitException extends SecurityException {
private int status = 0;
public int getStatus() {
return status;
}
private ExitException(){}
public ExitException(int status) {
this.status = status;
}
}
/**
* mainメソッド実装クラスをテストする基底クラス。
*/
public abstract class AbstractMainTester {
private static final String ARGS_DELIMITER = " ";
protected static final String LINE_SEPARATOR = System.getProperty("line.separator");
private static final PrintStream stdOut = System.out;
private static final PrintStream stdErr = System.err;
private static final SecurityManager securityManager = System.getSecurityManager();
/**
* 正常終了確認
*
* @return 標準出力
*/
protected String invorkeMainNomal(Class<?> cl, String arg, int exitCode) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setOut(new PrintStream(out));
invorkeMain(cl, arg, exitCode);
System.setOut(stdOut);
return out.toString();
}
/**
* 異常終了確認
*
* @return 標準エラー出力
*/
protected String invorkeMainError(Class<?> cl, String arg, int exitCode) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
System.setErr(new PrintStream(out));
invorkeMain(cl, arg, exitCode);
System.setErr(stdOut);
return out.toString();
}
/**
* mainメソッド実行
*/
private void invorkeMain(Class<?> cl, String arg, int exitCode) {
System.setSecurityManager(new TestSecurityManager());
try {
Method m = cl.getMethod("main", String[].class);
m.invorke(null, new Object[] { arg.split(ARGS_DELIMITER) });
} catch (InvocationTargetException ite) {
assertThat(((ExitException)ite.getTargetException()).getStatus(), is(exitCode));
} catch (Exception e) {
throw RuntimeException(e);
}
System.setSecurityManager(securityManager);
}
}