我同意这个问题没有得到很好的记录。
我设法编写了一个端到端测试,将服务器作为黑盒启动并发送 HTTP 请求。
它是这样工作的:
package com.project.org;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.tools.development.testing.BaseDevAppServerTestConfig;
import com.google.appengine.tools.development.testing.DevAppServerTest;
import com.google.appengine.tools.development.testing.DevAppServerTestRunner;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
@RunWith(DevAppServerTestRunner.class)
@DevAppServerTest(HelloWorldTest.TestConfig.class)
public class HelloWorldTest {
public class TestConfig extends BaseDevAppServerTestConfig {
@Override public File getSdkRoot() {
// You may need to tweak this.
return new File("../../appengine-java-sdk-1.9.15");
}
@Override public File getAppDir() {
return new File("war");
}
@Override
public List<URL> getClasspath() {
// There may be an easier way to do this.
List<URL> classPath = new ArrayList<>();
try {
String separator = System.getProperty("path.separator");
String[] pathElements = System.getProperty("java.class.path").split(separator);
for (String pathElement : pathElements) {
classPath.add(new File(pathElement).toURI().toURL());
}
}
catch (MalformedURLException e) {
throw new RuntimeException(e);
}
return classPath;
}
}
private final LocalServiceTestHelper testHelper;
private final String port;
public HelloWorldTest() {
testHelper = new LocalServiceTestHelper();
port = System.getProperty("appengine.devappserver.test.port");
}
@Before public void setUpServer() {
testHelper.setUp();
}
@After public void tearDown() {
testHelper.tearDown();
}
@Test public void testHelloWorld() throws Exception {
URL url = new URL("http://localhost:" + port + "/hello");
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(url);
assertEquals(200, response.getResponseCode());
assertEquals("Hello world!", new String(response.getContent(), "UTF-8"));
}
}
现在我遇到的问题是,如果您有两个这样的测试,每个测试都单独通过,您就不能在同一个二进制文件中运行它们。该文件第 37 行的异常被抛出:
IllegalStateException("Dev Appserver 已经在运行。")
不知道如何解决这个问题。