Search code examples
javaservletsjunitjunit4

JUnit - Run test cases from a web application


I have a set of test cases that are written in JUnit. Since there is a dependency on the servlet container for these test cases, I want to run them from a servlet. For example, if I pass the fully qualified class name of the Test class to the servlet, it should be able to run that test case. I have these test cases in the class path of web application.


Solution

  • /**
     * 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();
        }
    

    Above code helps us to invoke the JUnit test cases within the web application context.