这是我在 Java EE 环境中执行 JUnit 测试时使用的相当标准的方法。
基本思想是:
- 使用测试 Servlet 和您想要测试的任何 EJB 编写一个简单的测试应用程序
- 使用 JavaSE JUnit 测试套件启动应用程序服务器,并将 GET 请求驱动到测试 servlet
- 将您的实际测试逻辑放入测试 servlet 中,这样您的测试逻辑将在 Java EE 环境中执行
下面是它可能的样子的说明:
使用带有基本测试存根的 JUnit SE 套件来驱动对应用程序的 GET 请求:
@BeforeClass
public static void oneTimeSetUp() {
// start my app server and make sure apps are installed
}
@AfterClass
public static void oneTimeTearDown() {
// shut down app server
}
@Test
public void testApplicationAvailable() {
runTestInServlet("testApplicationAvailable");
}
@Test
public void testThatFails() {
runTestInServlet("testThatFails");
}
private void runTestInServlet(String testName) {
// Construct the URL, note that the name of the test is passed in
// as the value of the "test" parameter. This will get read from
// the servlet's doGet method
URL url = new URL("http://localhost:9080/myAppName/testServletName?test=" + test);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
try{
con.setRequestMethod("GET");
InputStream is = con.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// use the BufferedReader to validate response from test servlet
// i.e. search for some "successful test" token
} finally {
con.disconnect();
}
}
在测试servlet中使用相应的方法在Java EE环境中执行真正的测试:
@WebServlet(name = "TestServlet", urlPatterns = { "/testServletName" })
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String test = request.getParameter("test");
PrintWriter out = response.getWriter();
try {
System.out.println("-----> " + test + " starting");
// Use reflection to branch out and invoke the method found in the GET method's "test" parameter
getClass().getMethod(test, PrintWriter.class).invoke(this, response.getWriter());
System.out.println("<----- " + test + " successful");
} catch (Throwable x) {
System.out.println("<----- " + test + " failed:");
} finally {
out.flush();
out.close();
}
}
public void testApplicationAvailable(PrintWriter pw) throws Exception {
System.out.prinln("Application and test servlet available");
}
public void testThatFails(PrintWriter pw) throws Exception {
throw new Exception("This test will fail");
}
}
您可以使用第三方库来使这变得更简单,但这是基本思想。我在这里展示的示例都可以使用标准 Java 库(当然还有 Java EE 环境)来完成。这里唯一特定于您正在运行的应用程序服务器的内容是服务器启动和停止逻辑。
另外,我听说过有关 Arquillian 的好消息,但最后我听说它仅支持少数几个 Java EE 应用服务器,这会破坏您的可移植性要求。