简体   繁体   English

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

[英]JUnit - Run test cases from a web application

I have a set of test cases that are written in JUnit . 我有一组用JUnit编写的测试用例。 Since there is a dependency on the servlet container for these test cases, I want to run them from a servlet . 由于这些测试用例都依赖于servlet容器,因此我想从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. 例如,如果我将Test类的完全限定的类名传递给Servlet,则它应该能够运行该测试用例。 I have these test cases in the class path of web application. 我在Web应用程序的类路径中有这些测试用例。

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. 不确定为什么需要servlet容器,但是通常最好模拟环境,以便您可以控制并模拟不同的情况。

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 . 在下面的文档中,使用模拟框架(MOCKITO)对Servlet进行单元测试解释了如何使用Mockito对Servlet进行单元测试,这个问题也可能引起人们的兴趣,即如何使用JUnit测试我的Servlet

/**
 * 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. 上面的代码有助于我们在Web应用程序上下文中调用JUnit测试用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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