From the course: API Testing and Validation
Validate responses
- If you've been following along in this course so far, we've taken a simple story and added layers and tests to flesh it out, and make sure we're testing the right things in the right ways. So let's do it again. Going back to my last video, here's what we have. We have a very simple feature that's getting a list of issues from a repository. Skipping down to line 4, given I am an anonymous user, when I request issues from the "Symfony" repository from user "Symfony", then I should get at least one result. We're not going to change anything on this side this time around. Instead, let's think about what's happening behind the scenes. And the line that begins when I request a list of issues, our app is using some sort of HTTP connection, connecting to GitHub, and requesting issues from a repository. What if we had a typo, and instead of pointing at a valid user, valid repository, we point an invalid one? As is, that line would pass, and we'd be confused why we're getting zero results on the last line. So let's make our test a little bit more robust with a simple check of our HTTP status code. If we accidentally point at the wrong repository, we'd probably get a 404. So let's focus on the happy path of 200 OK. So, moving over to our editor, we can make a couple changes here. First of all, we want to get back our status code. Say, statusCode equals, we use the same HTTP GitHub client we had before. We want to get the LastResponse. And we want to get the StatusCode itself. And like I said, if it's anything other than a 200, we have a problem. So let's make this test very simple. If it's not equal to 200, let's throw an error. But let's be very specific with our error, and say "Expected a 200 status code but got statusCode instead!" Now, when we run this test, if all goes well, it should pass, exactly as it did before. And sure enough, it passes. But if we go back to our original story, of the feature description itself, we can make one change. We can add some garbage at the end of the string, and see what happens. And sure enough, it fails exactly where we expected it to. Now we have a safeguard earlier in our test, instead of waiting until the end. At first glance, this doesn't seem like a big deal. But now we have a very clear distinction between requesting a resource that doesn't exist, versus successfully requesting a resource with a count of zero. That level of specificity will become very important as we build more and deeper tests.