java - JUnit @before 执行程序

标签 java junit4

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

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

我怎样才能做到这一点?

最后我当然想终止这个进程。

最佳答案

你几乎已经回答了自己。您需要使用 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.

  }

}

关于java - JUnit @before 执行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26085096/

相关文章:

java - Junit 测试装置 - 初始化变量

java - OpenGL 渲染网格和旋转脚本不起作用?

multithreading - JUnit测试未执行测试中创建的所有线程

java - 如果测试用例失败,Selenium Web 驱动程序无法关闭 Firefox 实例

java - 看不到是什么导致了这个 Java 语法错误

java - 通过远程删除存储过程

java - 测试用例未涵盖在 cobertura 中

java - 在多个主机上并行执行

java - 将 Google Fonts 集成到我的 Android 应用程序中

java - 如何用 ImageIcon 完全填充 JButton 的表面?