简体   繁体   中英

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.

Not sure why you require a servlet container but usually it is better to mock the environment so that you are in control and can simulate different cases.

Within the following document 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();
    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM