JUnit - 从Web应用程序运行测试用例

时间:2016-04-08 17:15:29

标签: java servlets junit junit4

我有一组用JUnit编写的测试用例。由于这些测试用例依赖于servlet容器,因此我想从servlet运行它们。例如,如果我将Test类的完全限定类名传递给servlet,它应该能够运行该测试用例。 我在Web应用程序的类路径中有这些测试用例。

2 个答案:

答案 0 :(得分:2)

不确定为什么需要servlet容器,但通常最好是模拟环境以便控制并可以模拟不同的情况。

在以下文档Unit testing of servlet using mock framework (MOCKITO)中解释了如何使用mockito对servlet进行单元测试,这个问题也可能是有意义的How to test my servlet using JUnit

答案 1 :(得分:0)

/**
 * 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测试用例。

相关问题