(Re-published as a separate post)
In this post I will write a bit about programming EC2 using the Java library provided by AWS. In particular I was interested in the Mock capabilities already included in the library and how to use them, but unfortunately the documentation was a bit sparse on this topic.
Assume you want to do unit testing of an application using the AWS EC2 API or you are just in the middle of developing an application processing data from the API. In both cases you may want to use the mock capabilities included in the previously mentioned Java library, because it will reduce the time for running the tests or your application since no network communication is required. Instead, the mock mechanism will load AWS EC2 API responses from locally stored XML files and pretends to the library user that the response came from AWS. This example illustrates how to use the Mock functionality when using
AmazonEC2 service = new AmazonEC2Mock();.
The Mock responses are stored in src/com/amazonaws/ec2/mock with the file names represent the response object for the various API calls. For example, if we perform a DescribeInstances API call, the Mock response will be loaded from DescribeInstancesResponse.xml. The default content of these XML files will cause exceptions in the XML unmarshalling code, so do not be surprised. Unfortunately AWS do not provide reasonable responses, so we have to collect them ourselves.
Certain response objects can be converted to XML, but this output can not be used for the response XML files, because the response from the AWS API is transformed into the one we will have in the application. Therefore we have to obtain the raw response, which can be extracted by enabling DEBUG log output for the library (e.g. set rootLogger to DEBUG in src/log4j.properties and ant build dist the library) and execute regular API calls. For each API request you will see the AWS EC2 API response and the transformed response used by the application. Just copy the AWS API response XML into the appropriate Mock response file (someone should automate this approach).
After obtaining all relevant responses and storing them in the Mock files, your unit tests or application should run fine without exceptions when enabling the Mock service.