RESTful初探之六(testing)
Building and testing the service
Now that you know how you'll work with XML and already have a data layer to use, it's time to continue building your RESTful application with Restlets and do some test preparation.
现在你知道了如何使用XML和已经有了可以直接使用的数据层级,现在要开始构建RESTful应用了,先做点实践的准备。
The Races service
Recall that Acme Racing would like its service to enable clients to view existing races as well as create new ones.You've already outlined the RESTful URI that'll support this behavior:/race.
Via the Router class in the RaceApplication class, you linked this URI to the RacesResource class. You already know that you must implement three methods:
通过RaceApplication类,你将URI与RacesResource类链接起来,你需要实现下面三个方法。
*getRepresentation()
*allowPost()
*post()
Accordingly,create a class called RacesResource and ensure that it extends org.restlet.resource.Resource.Also,implement a three-parameter constructor,as shown in Listing13:
因此,创建RacesResource类并确定他继承org.restlet.resource.Resource。实现他拥有三个参数的构造方法如下:
In fact,this XML document is an example of what your RESTful Web service will return when the /race URI is invoked with a GET request.
事实上,这个XML是你的RESTful Web服务器将对/race URI GET请求返回的一个例子。
Therefore,your job is to link the retrieval of all race instances in the underlying data store; in fact ,at this point,you can already write a test.
Testing the service
Using the Restlet framework,you can construct a client instance and have it invoke your RESTful Web service.Moreover,you can leverage XMLUnit to verify that the service's output is some known XML document. Last, but not least, you can also use DbUnit (see Resources) to put the underlying database into a known state (so you can always get back the same XML
Using JUnit 4, you can create two fixtures that properly initialize XMLUnit and DbUnit, as shown in Listing 17:@Testpublic void getRaces() throws Exception { Client client = new Client(Protocol.HTTP); Response response = client.get("http://localhost:8080/racerrest/race/"); Diff diff = new Diff(new FileReader( new File("./etc/control-xml/control-web-races.xml")), new StringReader(response.getEntity().getText())); assertTrue(diff.toString(), diff.identical());}