Execute java program in separate thread before run

2019-05-23 18:13发布

问题:

I have an application that when the main method is executed, it starts a web server to host some RESTful services (using Dropwizard). I'm trying to write tests that access the HTTP methods (rather than the Java methods), so the tests have a prerequisite that the server is running.

Here is my task that executes the application and starts the web server:

task run (dependsOn: 'classes', type: JavaExec) {
    main = 'com.some.package.to.SomeService'
    classpath = sourceSets.main.runtimeClasspath
    args 'server', 'some.yml'
}

The server takes a few seconds to start up, too. Roughly, what I want to do is something like this:

test.doFirst {
    println "Starting application..."
    Thread.startDaemon {
        // What goes here???
    }
    sleep 20000
    println "Application should be started."
}

In other words, before running tests, start the application in a separate thread and wait some time before running tests, giving it time to finish starting up.

That said, I can't figure out what goes in Thread.startDaemon (tasks.run.execute() doesn't work), nor if this is even the best approach. What would be the best way of going about this?

Thanks!

回答1:

What I would probably do is something like this:

task startServer (type: Exec) {
    workingDir 'tomcat/bin'
    // using START hopefully forks the process
    commandLine 'START', 'start.bat'
    standardOutput = new ByteArrayOutputStream()
    ext.output = {
      return standardOutput.toString()
    }
    // loop through output stream for finished flag
    // or just put a timeout here
}

task testIt (type: Test) {
    description "To test it."
    include 'org/foo/Test*.*'
}

Then, when calling Gradle targets, call "gradle.bat startServer testIt" . That is the basic idea.



标签: groovy gradle