In every testing framework we do data setup and clean up. Below is how I do it with Gradle framework:
Global Data Setup
Pact framework provides very good random test data generation with PactBodyBuilder. However, in some cases where our API involves data creation, we will need to remember the data we created, so we can use it across multiple tests, and then deleting it afterwards.
We can do this by using System Property in Gradle. Under test section in build.gradle, include this:
test{ systemProperty 'RandomNum', new Random(1000) }
In the Pact Consumer test where you need to create the data, do this:
- Define the random number data that you want to generate and remember
class InsertCFCertConsumerTests { def ran=System.getProperty("RandomNum") @Test void "Insert CF Certificate" (){
- In the Pact body, include your random number
withBody{ requestId ran }
- Of course, include this random number in the 2nd part of the Consumer test (service run)
VerificationResult result = CF_service.run() { def client = new RESTClient('http://localhost:1237/') def body = new JsonBuilder([requestId: ran]) def cf_response = client.post(path: '/v1/carfacts/',requestContentType: 'application/json',headers:['Content-Type': 'application/json'],body:body.toPrettyString())
- The same random number ran can be called across multiple tests
Cleanup
To clean up data from database, create a task in build.gradle.
Clean up via database
- Connect to the database
task cleanUp<<{ gradle.class.classLoader.addURL(new File('src/main/resources/ojdbc6.jar').toURI().toURL()) def sql = Sql.newInstance('jdbc:oracle:thin:@testDatabase.oracle.csuat.com.au:1521/test.test.office', 'USERNAME', 'PASSWORD', 'oracle.jdbc.driver.OracleDriver') }
ojdbc6.jar is the Oracle database driver downloaded from the Oracle site . External file can be included during compilation by adding the following line under dependencies:
dependencies { compile files('src/main/resources/ojdbc6.jar') }
- Write the SQL to delete the data you want
String sqlDelete = 'delete from Table where id='VN000000000000001''
- Execute the query
sql.execute(sqlDelete)
Clean up via API call
Sometimes, we could call a DELETE via API to do data clean up.
- Get Id via database and delete via API call
task cleanUp<<{ String sqlGetId= 'select id from Table where id='VN000000000000001''def delElas=new RESTClient('http://test.domain.com.au:9200') def cfId=0 sql.eachRow(sqlGetId) { println it.id cfId=it.id delElas.delete(path:"/id_checker/${cfId}") } }
However, please note that the above will cause build task to fail as the data that you want to delete will not exist. Workaround for this is to exclude this task while building via command gradle build -x <name of clean up task>.
Leave a Reply