我四处研究,似乎找不到任何体面的资源来帮助我 JUnit 测试用 Java 编写的 apache commons 守护程序。我希望能够测试当一个守护进程启动时它不会失败地启动,而当它关闭时它的关闭不会失败。
这是守护程序在一段时间后启动和停止的一些示例代码:
更新
public class MyDaemon implements Daemon
{
private Logger myLogger = LogManager.getLogger(FileLoggerImpl.class);
private List<FileLogger> loggers;
private List<Thread> threads;
public void init(DaemonContext arg0) throws DaemonInitException, Exception
{
myLogger.info("Starting Logger");
loggers = new ArrayList<FileLogger>();
threads = new ArrayList<Thread>();
myLogger.info("Finished starting Logger");
}
public void start() throws Exception
{
if(threads.size()>0 || loggers.size()>0)
stop();
for(int i = 0; i < 1; i++)
{
FileLogger logger = new FileLoggerImpl(Integer.toString(i));
Thread thread = new Thread(logger);
loggers.add(logger);
threads.add(thread);
thread.start();
}
}
public void stop() throws Exception
{
myLogger.info("Cleaning up threads...");
for(int i = 0; i < 1; i++)
{
FileLogger logger = loggers.get(i);
Thread thread = threads.get(i);
logger.isExecuting(false);
thread.join();
}
myLogger.info("Stopping thread");
}
public void destroy()
{
myLogger.info("Destroying resources...");
loggers = null;
threads = null;
myLogger.info("Destroyed resources.");
}
public static void main(String argsv[])
throws Exception
{
MyDaemon myDaemon = new MyDaemon();
myDaemon.init(null);
myDaemon.start();
Thread.sleep(30000);
myDaemon.stop();
}
}
Logger 类读入一个文本文件并将该文本文件中的随机行写入日志文件 *
public void run()
{
String fileLocation = "/textFileLocation";
while(isExecuting)
{
try {
logger.info(getRandomLineOpt(fileLocation));
} catch (IOException e) {
logger.warn("File :" + fileLocation +" not found!");
e.printStackTrace();
}
pause(DELAY_SECONDS);
}
}
public String getRandomLine(String fileLoc) throws IOException
{
BufferedReader reader = new BufferedReader(new FileReader(fileLoc));
//Commons IO
ArrayList<String> lines = new ArrayList<String>();
String line =null;
while( (line = reader.readLine())!= null )
lines.add(line);
return lines.get(new Random().nextInt(lines.size()));
}
非常感谢任何帮助。