How (not) to test RESTful APIs with Selenium WebDriver
This post was published on September 28, 2016I’ve seen the question of how to do RESTful API testing with Selenium WebDriver come up a lot in various places. I’ve seen it mainly on LinkedIn, but a couple of weeks ago I was asked this question in person as well. So, as your ever helpful consultant, I thought I’d be a good idea to show you how it’s done.
First, let’s create a new browser driver object. For the sake of simplicity, I’ll use Firefox, because it doesn’t require setting up a separate driver. And yes, I know implicit waits aren’t the best waiting strategy, but I didn’t feel like writing an ExpectedCondition.
driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Now, instead of browsing to a web page, we’ll simply browse to the RESTful API endpoint for which we want to check the response. I’ll use api.zippopotamus.us as an example here to look up some data for the US zip code 90210:
driver.get("http://api.zippopotam.us/us/90210");
This gives us the following output:
Let’s grab the text we see on screen and convert it to a JSON object (using the org.json package):
WebElement element = driver.findElement(By.xpath("//pre")); JSONObject jsonObject = new JSONObject(element.getText());
Now that we have a JSON object containing the API response, we can extract specific elements and check their value:
String valueToCheck = jsonObject.get("country").toString(); Assert.assertEquals(valueToCheck, "United States");
As a final step, throw everything away, never do this again and please forget everything you’ve seen so far in this post. Selenium is not an API testing tool. It has never been, and it will never be. So please don’t try and force it to be.
Please stick to simulating UI interaction when using Selenium and use a dedicated, fit for purpose tool for API testing. As an example, REST Assured can perform the exact same check as the above. With a single line of code. Which is far better readable to boot:
@Test public void doRestTestProperly() { given(). when(). get("http://api.zippopotam.us/us/90210"). then(). assertThat(). body("country", equalTo("United States")); }
So, here’s to hoping I did my part in exterminating questions that feature ‘Selenium’ and ‘API testing’ in the same sentence.
"