1

私はいろいろ調べましたが、Java で書かれた apache commons デーモンを JUnit でテストするのに役立つ適切なリソースが見つからないようです。デーモンが起動すると必ず起動し、シャットダウンすると必ずシャットダウンすることをテストできるようにしたいと思います。

以下は、ピリオドの後に開始および停止するデーモンのコード例です。

アップデート

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();

        }

}

ロガー クラスはテキスト ファイルを読み取り、このテキスト ファイルからランダムな行をログ ファイルに書き込みます *

    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()));
    }

どんな助けでも大歓迎です。

4

1 に答える 1