Wednesday, July 18, 2012

How to test Restlet webservice using JUnit without deploying webservice in webserver

How to test Restlet web service using JUnit without deploying web service in web server


1. create a class to load all bean xml files extending Application

public class WebServiceServer extends Application {

    /**
     * Creates a root Restlet that will receive all incoming calls.
     */
    @Override
    public synchronized Restlet createInboundRoot() {
        // Create a router Restlet that routes each call to a
        // new instance of HelloWorldResource.

        File contextDir = new File(System.getProperty("user.dir"));
        if (!contextDir.getName().equals("context")) {
            contextDir = new File(contextDir, "context");
        }

        if (!contextDir.isDirectory()) {
            throw new IllegalStateException("Could not find context directory");
        }
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
                new String[] {contextDir + "\\WEB-INF\\beans\\WebService-servlet.xml" });
        SpringRouter router = context.getBean("root", SpringRouter.class);

        // Defines only one route
        router.attach("/webservice", ActualRestletClass.class);

        return router;
    }
}


2. WebService-servlet.xml file config


       
           
               
               
                   
                       
                   

               

           

       

   


   
     


3. Actual restlet webservice

public class ServiceResource extends ServerResource {
@Override
    protected Representation get(Variant variant) throws ResourceException {


Representation resource = new StringRepresentation(content, mediaType);
    return resource;
    }}

}

4. Now test your restlet

 public class TestWebService {
    public static void main(String[] args) throws Exception {
        // Create a new Component.
        Component component = new Component();
        // Add a new HTTP server listening on port 8182.
        component.getServers().add(Protocol.HTTP, 8182);
    
        // Attach the sample application.
        component.getDefaultHost().attach("/WebService",
                new WebServiceServer());
        // Start the component.
        component.start();
    }
}




No comments: