JUnit执行程序@before

时间:2014-09-28 13:01:18

标签: java junit4

我正在使用JUnit,现在我想在运行测试之前执行Java程序(main方法)。

即。在我的项目中,我有一个包含一个主要方法的类的包。我想在运行测试之前运行(可能在一个单独的进程中),因为测试中的类将通过套接字连接到他的进程。

我该怎么做?

最后我想杀死这个过程。

1 个答案:

答案 0 :(得分:1)

你几乎已经回答了自己。您需要使用Runtime.exec()(http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html)或一些更复杂的工具(如Apache Commons Exec http://commons.apache.org/proper/commons-exec/index.html

)在单独的线程中启动此过程

使用'@Before'或'@BeforeClass'注释注释的方法可以是这样做的好地方。最好的方法是将额外的辅助类编程为单例。这个类只负责在以前没有启动的情况下启动线程,因此所有测试只有一个进程。


编辑:应该是这样的:

 @BeforeClass
  public static void startProess() throws Exception {
    SomeProcess .getInstance().startIfNotRunning();
  }

public class SomeProcess {
  private Thread thread;
  private Process process;


  private static SomeProcess instance = new SomeProcess ();
  public static SomeProcess getInstance() {
    return instance;
  }

  public synchronized void startIfNotRunning() throws Exception {
      (...) 
      // check if it's not running and if not start
      (...)
      instance.start();
      (...)
  }

  public synchronized void stop() throws Exception {
      process.destroy()
  }

 private synchronized void start() throws Exception {
    thread = new Thread(new Runnable() {
        @Override
        public void run() {
           process = Runtime.exec("/path/yo/your/app");
        }

      });


    thread.start();

    // put some code to wait until the process has initialized (if it requires some time for initialization.

  }

}
相关问题