API Testing using RestAssured | Code Example

APIs are playing an ever more important role in software trends. Testing and validating REST APIs in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of using these languages into the Java domain. REST Assured is a Java library that provides a domain-specific language for writing powerful, maintainable tests for RESTful APIs.

Code Example 1| GET

import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;

public class GetData {
	
	@Test
	public void testResponsecode()
	{
		Response resp = RestAssured.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907");		
		int code=resp.getStatusCode();		
		System.out.println("Status code is "+code);		
		Assert.assertEquals(code, 200);
	}
	
	@Test
	public void testBody()
	{
		Response resp = RestAssured.get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907");		
		String data=resp.asString();	
		System.out.println("Data is "+data);		
		System.out.println("Response time "+resp.getTime());
	}
}

Code Example 2| GET

import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;

public class GetData2 {
	
	@Test
	public void testResponsecode()
	{	
		int code = get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907").getStatusCode();	
		System.out.println("Status code is "+code);
		Assert.assertEquals(code, 200);
	}
	
	@Test
	public void testBody()
	{	
		String data = get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907").asString();		
		long time = get("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907").getTime();
		System.out.println("Data is "+data);
		System.out.println("Response time "+time);
	}		
} 

This is a open-source international community to improve software testing practices, send your post here

Advertisements

Leave a Reply