JUnit - 来自 Web 应用程序的 运行 个测试用例
JUnit - Run test cases from a web application
我有一组用JUnit
编写的测试用例。由于这些测试用例依赖于 servlet 容器,我想从 servlet
中 运行 它们。例如,如果我将测试 class 的完全限定 class 名称传递给 servlet,它应该能够 运行 该测试用例。
我在 Web 应用程序的 class 路径中有这些测试用例。
不确定为什么需要 servlet 容器,但通常最好模拟环境,这样您就可以控制并模拟不同的情况。
在以下文档中 Unit testing of servlet using mock framework (MOCKITO) is explained how to unit test servlets using mockito, and this question can also be of interest How to test my servlet using JUnit。
/**
* The various JUNIT classes should be passed as the <code>class</code> request paramter in the URL.
* @param request
* @param response
*/
private void executeJUNITTestCases( HttpServletRequest request, HttpServletResponse response ){
response.setContentType( "text/plain" );
//Pass the class names of the Test cases in the URL parameter "class"
String[] className = request.getParameterValues( "class" );
try{
if( className = null || className.length == 0){
PrintWriter writer = response.getWriter();
JSONObject obj = new JSONObject();
obj.put( "error", "Class names should be provided as parameter values of key [class]" );
writer.write( obj.toString() );
return;
}
OutputStream out = response.getOutputStream();
final PrintStream pout = new PrintStream( out );
new JUnitCore().runMain( new JUnitSystem(){
public PrintStream out(){
return pout;
}
public void exit( int arg0 ){}
}, className );
out.close();
}
catch( IOException e ){
e.printStackTrace();
}
以上代码帮助我们在 Web 应用程序上下文中调用 JUnit 测试用例。
我有一组用JUnit
编写的测试用例。由于这些测试用例依赖于 servlet 容器,我想从 servlet
中 运行 它们。例如,如果我将测试 class 的完全限定 class 名称传递给 servlet,它应该能够 运行 该测试用例。
我在 Web 应用程序的 class 路径中有这些测试用例。
不确定为什么需要 servlet 容器,但通常最好模拟环境,这样您就可以控制并模拟不同的情况。
在以下文档中 Unit testing of servlet using mock framework (MOCKITO) is explained how to unit test servlets using mockito, and this question can also be of interest How to test my servlet using JUnit。
/**
* The various JUNIT classes should be passed as the <code>class</code> request paramter in the URL.
* @param request
* @param response
*/
private void executeJUNITTestCases( HttpServletRequest request, HttpServletResponse response ){
response.setContentType( "text/plain" );
//Pass the class names of the Test cases in the URL parameter "class"
String[] className = request.getParameterValues( "class" );
try{
if( className = null || className.length == 0){
PrintWriter writer = response.getWriter();
JSONObject obj = new JSONObject();
obj.put( "error", "Class names should be provided as parameter values of key [class]" );
writer.write( obj.toString() );
return;
}
OutputStream out = response.getOutputStream();
final PrintStream pout = new PrintStream( out );
new JUnitCore().runMain( new JUnitSystem(){
public PrintStream out(){
return pout;
}
public void exit( int arg0 ){}
}, className );
out.close();
}
catch( IOException e ){
e.printStackTrace();
}
以上代码帮助我们在 Web 应用程序上下文中调用 JUnit 测试用例。