Application of REST in Automation Testing

9189 단어 automation
background:
In the process of web automation testing (eg. Selenium), the test code and the Application code are separated. That is to say, the code of the automated test cannot call the Application code. Just use the application's web container when the test case is running.
This will encounter a problem. Some functions in the Application need to be executed in the background service to obtain data. These services are generally executed regularly. In automated tests, such as clicking some buttons on the page, if you want to see the data on the page, you need to wait for the service to execute before you can see the data. The execution cycle of some services may be 24 hours. Obviously you can't let the test case wait 24 hours before checking the data.
 
solution:
For the above problems, the solution that is easy to think of is to explicitly call the application's background service during the execution of the test case. As mentioned earlier, the test code is the code that cannot call the application. So what to do?
A general solution is to encapsulate the service function of the application into a standard interface, such as web service, REST, etc., and open it to the outside world. Then call these standard web services or REST interfaces in test. This solves the dependency problem.
 
Implementation:
Here we take REST as an example to introduce the method of encapsulating the application background service into a RESTFul interface. In the actual development process, there will be many background services. As the system is upgraded, new services may be added. If every time a service is added, a RESTful interface is opened, the system will become more and more cumbersome. And some development is in the form of plugin, and it is not allowed to add Restful interface.
This needs to be taken into account when the system is designed. How to do it? A RESTful interface is defined in Application core to be open to the outside world. Internal processing takes place in this open interface. The method is to define an extensible REST Service interface, and load the concrete class that implements the REST Service interface through the java.util.ServiceLoader of JDK. Trigger the corresponding REST Service according to the serviceName specified in the URL.
Take Apache Wink Framework as an example to introduce the method of deploying RESTful API
--------------------------RESTful interface in Application core------------------- ------------------------------------


package com.mycompany.rest;

@Path("/automation/AutomationServiceTest")
public class TestingRestfulResource {

    private static Map<String, AutomationServiceTest> serviceTestMap =
            new HashMap<String, AutomationServiceTest>();

 

    static {
        ServiceLoader<AutomationServiceTest> driverProvider =
                ServiceLoader.load(AutomationServiceTest.class);
        for (AutomationServiceTestserviceTest : driverProvider) {
            serviceTestMap.put(serviceTest.getServiceName(), serviceTest);
        }

    }

    @GET
    @Produces({MediaType.TEXT_PLAIN, MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public Object runService(@Context final HttpServletRequest request)
            throws WSException
    {
        // The service name like "AgileSyncService"
        String serviceName = request.getParameter("serviceName");
        AutomationServiceTest serviceTest = serviceTestMap.get(serviceName);
        if (null == serviceTest) {
            log.error("Service " + serviceName + "not found");
            throw new WSException(Response.Status.INTERNAL_SERVER_ERROR, request,
                    WSErrorHelper
                            .createWSError("INT_SERVICE_NOT_FOUND", new String[] {serviceName}));
        }
        return serviceTest.runService(request);
    }

}

Add a line to wink_ws.app file
com.mycompany.rest.TestingRestfulResource
 
-------------------------AutomationServiceTest interface ----------------------- --------------


package com.mycompany.test.plugin.rest.service;

 

import javax.servlet.ServletRequest;

public interface AutomationServiceTest {
    public Object runService(ServletRequest request);

    public String getServiceName();
}

 


----------------------RESTful service implementation class----------------------- --------------------


package com.mycompany.test.plugin.rest.service.impl

 

public class MyServiceTestImpl implements AutomationServiceTest {

    @Override
    public Object runService(ServletRequest request) {
        MyService service = new MyService ();
        service.runService("jobID", 2L, 2L);
        return "<result>run my service successfully</result>";
    }

    @Override
    public String getServiceName() {
        return "MyService";
    }

}
 

Add a line to the/META-INF/services/com.mycompany.test.plugin.rest.service.AutomationServiceTest file
com.mycompany.test.plugin.rest.service.impl.MyServiceTestImpl
-------------------------------------------------- -------------------------------------------------- ---------------
 
This way, via the URL:
http://localhost:8080//rest/automation/AutomationServiceTest?serviceName=MyService
You can call the RESTful interface in the code of Automation Testing, and then trigger the background servie.
For example, using the Cactus framework, test code can be written as follows.
 
package com.mycompany.webdriver.page.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.junit.Before;
import org.junit.Test;

 

 

public class TestMyServic {

      private static final String SERVICE_URL = "http://localhost:8080/app/rest/automation/AutomationServiceTest?serviceName=MyService";

 

    private DefaultHttpClient client;
    private HttpGet get;  
  
   
    @Before
    public void setup() {
        //For REST API Call
        client = new DefaultHttpClient();
        //set time out
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
        client.setParams(params);

        get = new HttpGet();

    }

 

    @Test
    public void testCallService() {
       
        System.out.println("begin............");
       
        get.setURI(URI.create(SERVICE_URL));
        
        HttpResponse response;
        try {
            response = client.execute(get);
            String responseText = getHttpResponseBodyContent(response);
           
            System.out.println("******response: " + responseText);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       
       
        System.out.println("end............");
       
    }
   

   
    private static String getHttpResponseBodyContent(HttpResponse response) throws IllegalStateException, IOException{
        String result = null;
       
        BufferedReader bufferedReader = null;
        try{
            bufferedReader = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));
           
            StringBuilder sb = new StringBuilder();
            String outputLine;
           
            while ((outputLine = bufferedReader.readLine()) != null) {
                sb.append(outputLine);
            }
           
            result = sb.toString();
        }finally{
            bufferedReader.close();
        }
       
        return result;
    }

 

}

좋은 웹페이지 즐겨찾기