Test a REST API with Java | Baeldung

<br>

Table of Contents
  • 1. Overview
  • 2. Testing the Status Code
  • 3. Testing the Media Type
  • 4. Testing the JSON Payload
  • 5. Utilities for Testing
  • 6. Dependencies
  • 7. Conclusion


1. Overview

This tutorial focuses on the basic principles and mechanics of testing a REST API with live Integration Tests (with a JSON payload).

The main goal is to provide an introduction to testing the basic correctness of the API – and we’re going to be using the latest version of the GitHub REST API for the examples.

For an internal application, this kind of testing will usually run as a late step in a Continuous Integration process, consuming the REST API after it has already been deployed.

When testing a REST resource, there are usually a few orthogonal responsibilities the tests should focus on:

  • the HTTP response code
  • other HTTP headers in the response
  • the payload (JSON, XML)

Each test should only focus on a single responsibility and include a single assertion. Focusing on a clear separation always has benefits, but when doing this kind of black box testing it’s even more important, as the general tendency is to write complex test scenarios in the very beginning.

Another important aspect of the integration tests is adherence to the Single Level of Abstraction Principle – the logic within a test should be written at a high level. Details such as creating the request, sending the HTTP request to the server, dealing with IO, etc should not be done inline but via utility methods.


2. Testing the Status Code


@Test
public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived()
  throws ClientProtocolException, IOException {
  
   // Given
   String name = RandomStringUtils.randomAlphabetic( 8 );
   HttpUriRequest request = new HttpGet( "https://api.github.com/users/" + name );
 
   // When
   HttpResponse httpResponse = HttpClientBuilder.create().build().execute( request );
 
   // Then
   assertThat(
     httpResponse.getStatusLine().getStatusCode(),
     equalTo(HttpStatus.SC_NOT_FOUND));
}


This is a rather simple test – it verifies that a basic happy path is working, without adding too much complexity to the test suite.

If for whatever reason, it fails, then there is no need to look at any other test for this URL until this is fixed.


3. Testing the Media Type


@Test
public void
givenRequestWithNoAcceptHeader_whenRequestIsExecuted_thenDefaultResponseContentTypeIsJson()
  throws ClientProtocolException, IOException {
  
   // Given
   String jsonMimeType = "application/json";
   HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );
 
   // When
   HttpResponse response = HttpClientBuilder.create().build().execute( request );
 
   // Then
   String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
   assertEquals( jsonMimeType, mimeType );
}


4. Testing the JSON Payload
@Test
public void
  givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect()
  throws ClientProtocolException, IOException {
  
    // Given
    HttpUriRequest request = new HttpGet( "https://api.github.com/users/eugenp" );
 
    // When
    HttpResponse response = HttpClientBuilder.create().build().execute( request );
 
    // Then
    GitHubUser resource = RetrieveUtil.retrieveResourceFromResponse(
      response, GitHubUser.class);
    assertThat( "eugenp", Matchers.is( resource.getLogin() ) );
}


In this case, I know the default representation of GitHub resources is JSON, but usually, the Content-Type header of the response should be tested alongside the Accept header of the request – the client asks for a particular type of representation via Accept, which the server should honor.


5. Utilities for Testing

We’re going to use Jackson 2 to unmarshall the raw JSON String into a type-safe Java Entity:

public class GitHubUser {
 
    private String login;
 
    // standard getters and setters
}


We’re only using a simple utility to keep the tests clean, readable and at a high level of abstraction:

public static <T> T retrieveResourceFromResponse(HttpResponse response, Class<T> clazz) 
  throws IOException {
  
    String jsonFromResponse = EntityUtils.toString(response.getEntity());
    ObjectMapper mapper = new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return mapper.readValue(jsonFromResponse, clazz);
}


Notice that Jackson is ignoring unknown properties that the GitHub API is sending our way – that’s simply because the Representation of a User Resource on GitHub gets pretty complex – and we don’t need any of that information here.

6. Dependencies

The utilities and tests make use of the following libraries, all available in Maven central:

  • HttpClient
  • Jackson 2
  • Hamcrest (optional)

7. Conclusion

This is only one part of what the complete integration testing suite should be. The tests focus on ensuring basic correctness for the REST API, without going into more complex scenarios,

For example, the following are not covered: Discoverability of the API, consumption of different representations for the same Resource, etc.



Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

Learn Java Programming | Java Complete Tutorial for Beginners | Simpliv

This program on Java programing from Simpliv’s experts uses Java and an Integrated Development Environment (IDE). Just download this, with their help of course, and open your way to hundreds of lines of source code, and hundreds of lines of comments. That is some Java programming learning!

Description
Taught by a Stanford-educated, ex-Googler, husband-wife team
This course will use Java and an Integrated Development Environment (IDE). Never fear, we have a detailed video on how to get this downloaded and set up.
Hundreds of lines of source code, and hundreds of lines of comments - just download and open in your IDE!
A Java course for everyone - accessible yet serious, to take you from absolute beginner to an early intermediate level

Let’s parse that.

This is a Java course for everyone. Whether you are a complete beginner (a liberal arts major, an accountant, doctor, lawyer) or an engineer with some programming experience but looking to learn Java - this course is right for you.
The course is accessible because it assumes absolutely no programming knowledge, and quickly builds up using first principles alone
Even so, this is a serious Java programming class - the gradient is quite steep, and you will go from absolute beginner to an early intermediate level
The course is also quirky. The examples are irreverent. Lots of little touches: repetition, zooming out so we remember the big picture, active learning with plenty of quizzes. There’s also a peppy soundtrack, and art - all shown by studies to improve cognition and recall.
What's Covered:

Programming Basics: What programming is, and a carefully thought-through tour of the basics of any programming. Installing and setting up an IDE and writing your first program
The Object-Oriented Paradigm: Classes, Objects, Interfaces, Inheritance; how an OO mindset differs from a functional or imperative programming mindset; the mechanics of OO - access modifiers, dynamic dispatch, abstract base classes v interfaces. The underlying principles of OO: encapsulation, abstraction, polymorphism
Threading and Concurrency: A deep and thorough study of both old and new ways of doing threading in Java: Runnables, Callables, Threads, processes, Futures, Executors.
Reflection, Annotations: The how, what and why - also the good and bad
Lambda Functions: Functional constructs that have made the crossover into the mainstream of Java - lambda functions, aggregate operators.
Modern Java constructs: Interface default methods; properties and bindings too. Also detailed coverage of Futures and Callables, as well as of Lambda functions, aggregation operators. JavaFX as contrasted with Swing.
Packages and Jars: The plumbing is important to understand too.
Language Features: Serialisation; why the Cloneable interface sucks; exception handling; the immutability of Strings; the Object base class; primitive and object reference types; pass-by-value and pass-by-object-reference.
Design: The MVC Paradigm, Observer and Command Design Patterns.
Swing: Framework basics; JFrames, JPanels and JComponents; Menus and menu handling; Trees and their nuances; File choosers, buttons, browser controls. A very brief introduction to JavaFX.
Programming Drills (code-alongs, with source code included)

Serious stuff:
A daily stock quote summariser: scrapes the internet, does some calculations, and outputs a nice, formatted Excel spreadsheet.
A News Curation app to summarise newspaper articles into a concise email snippet using serious Swing programming
Simple stuff:
Support with choosing a programming environment; downloading and setting up IntelliJ.
Simple hello-world style programs in functional, imperative and object-oriented paradigms.
Maps, lists, arrays. Creating, instantiating and using objects, interfaces
Who is the target audience?

Yep! Folks with zero programming experience - liberal arts majors, doctors, accountants, lawyers
Yep! Engineering students from non-CS majors looking to learn fairly serious programming
Nope! Experienced Java programmers - this class will be boring for you:)
Yep! Computer Science students or software engineers with no experience in Java, but experience in Python, C++ or even C#. You might need to skip over some bits, but in general the class will still have new learning to offer you :-)
Basic knowledge
No prior programming experience needed:)
The class will make use of Java and an IDE - never fear, we have a detailed video to walk you through the process of setting this up
What will you learn
Write Java programs of moderate complexity and sophistication (at an early to middling intermediate level)
Understand Object-Oriented programming concepts at the level where you can have intelligent design conversations with an experienced software engineer
Manage concurrency and threading issues in a multi-threaded environment
Create and modify files (including Excel spreadsheets) and download content from the internet using Java
Use Reflection, Annotations, Lambda functions and other modern Java language features
Build serious UI applications in Swing
Understand the Model-View-Controller paradigm, the Observer and Command Design patterns that are at the heart of modern UI programming
Gain a superficial understanding of JavaFX and Properties and Bindings
Understand the nuances of Java specific constructs in serialisation, exception-handling, cloning, the immutability of strings, primitive and object reference types
To continue:

Free Java Programming for Complete Beginners in 250 Steps | Simpliv

Free Java Programming for Complete Beginners in 250 Steps | Simpliv

Free Java Programming for Complete Beginners in 250 Steps

Description
We love Programming. Our aim with this course is to create a love for Programming.

Java is one of the most popular programming languages. Java offers both object oriented and functional programming features.

We take an hands-on approach using a combination of JShell(An awesome new feature in Java 9) and Eclipse as an IDE to illustrate more than 200 Java Coding Exercises, Puzzles and Code Examples.

In more than 250 Steps, we explore the most important Java Programming Language Features

Basics of Java Programming - Expressions, Variables and Printing Output
Java Operators - Java Assignment Operator, Relational and Logical Operators, Short Circuit Operators
Java Conditionals and If Statement
Methods - Parameters, Arguments and Return Values
Object Oriented Programming - Class, Object, State and Behavior
Basics of OOPS - Encapsulation, Abstraction, Inheritance and Polymorphism
Basics about Java Data Types - Casting, Operators and More
Java Built in Classes - BigDecimal, String, Java Wrapper Classes
Conditionals with Java - If Else Statement, Nested If Else, Java Switch Statement, Java Ternary Operator
Loops - For Loop, While Loop in Java, Do While Loop, Break and Continue
Immutablity of Java Wrapper Classes, String and BigDecimal
Java Dates - Introduction to LocalDate, LocalTime and LocalDateTime
Java Array and ArrayList - Java String Arrays, Arrays of Objects, Primitive Data Types, toString and Exceptions
Introduction to Variable Arguments
Basics of Designing a Class - Class, Object, State and Behavior. Deciding State and Constructors.
Understanding Object Composition and Inheritance
Java Abstract Class and Interfaces. Introduction to Polymorphism.
Java Collections - List Interface(ArrayList, LinkedList and Vector), Set Interface (HashSet, LinkedHashSet and TreeSet), Queue Interface (PriorityQueue) and Map Interface (HashMap, HashTable, LinkedHashMap and TreeMap() - Compare, Contrast and Choose
Generics - Why do we need Generics? Restrictions with extends and Generic Methods, WildCards - Upper Bound and Lower Bound.
Functional Programming - Lambda Expression, Stream and Operations on a Stream (Intermediate Operations - Sort, Distinct, Filter, Map and Terminal Operations - max, min, collect to List), Functional Interfaces - Predicate Interface,Consumer Interface, Function Inteface for Mapping, Method References - static and instance methods
Introduction to Threads and MultiThreading - Need for Threads
Implementing Threads - Extending Thread Class and Implementing Runnable Interface
States of a Thread and Communication between Threads
Introduction to Executor Service - Customizing number of Active Threads. Returning a Future, invokeAll and invokeAny
Introduction to Exception Handling - Your Thought Process during Exception Handling. try, catch and finally. Exception Hierarchy - Checked Exceptions vs Unchecked Exceptions. Throwing an Exception. Creating and Throwing a Custom Exception - CurrenciesDoNotMatchException. Try with Resources - New Feature in Java 7.
List files and folders in Directory with Files list method, File walk method and find methods. Read and write from a File.
Who is the target audience?

You want to learn Programming
You are a beginner and want to explore Java further
You want to learn the basics of Object Oriented Programming with Java
You want to learn the basics of Functional Programming with Java
Basic knowledge
Connectivity to Internet to download Java 9 and Eclipse.
We will help you install Eclipse and Java 9
Oracle Solaris or 64 bit Microsoft Windows or Linux or macOS
Java 9 does NOT work on 32 bit Microsoft Windows! You would need a 64 bit Microsoft Windows if you would want to use Windows.
What will you learn
You will learn how to think as a Java Programmer
You will learn how to start your journey as a Java Programmer
You will learn the basics of Eclipse IDE and JShell
You will learn to develop awesome object oriented programs with Java
You will solve a wide variety of hands-on exercises with Java
You will learn the basics of programming - variables, choosing a data type, conditional execution, loops, writing great methods, breaking down problems into sub problems and implementing great Exception Handling
You will learn the basics of Object Oriented Programming - Intefaces, Inheritance, Abstract Class and Constructors
You will learn the important concepts of Object Oriented Programming - Abstraction, Inheritance, Encapsulation and Polymorphism
You will learn to do basic functional programming with Java
You will learn the basics of MultiThreading - with Executor Service
You will learn about a wide variety of Collections - List, Map, Set and Queue Interfaces
To continue:

Java Essentials : Learn Core Java From Basic to Advance

Java Essentials : Learn Core Java From Basic to Advance

Learn Java Programming Using Practical Assignments. Start Building Back-end Web Applications Robust Test Automation Frameworks By End Of The Course. Learn More!

Description
This is only Java related course and it's great because it covers just the right amount of Java which is needed to leaning programming, java.

This is a comprehensive yet simple course on java programming language and it concentrates on Java programming concepts.

*************************** No Prior Coding Experience Needed ***************************

This course assumes that you have no programming background. If you have some experience then, it's just a bonus point. You have never code, have some experience or have a lot of experience any other programming language, this course is one stop place for you.

Java is one of the most and useful programming languages to learn You can build back-end of web applications and build robust test automation framework. Specially for Selenium WebDriver GUI automation, Java is most popular choice and has the largest community.

Each lecture consist of a video screencast and code files

There are quizzes, homework to test your knowledge

High focus on practice and asking questions

You will also learn coding best practices

Market is never short of jobs in Java programming language, there are ample of jobs in both Java development and Automation Testing using Java.

What are you waiting for? Enroll today and learn the powerful Java language !!!

Basic knowledge
Nothing else! It’s just you, your computer and your hunger to get started today
Java concepts are covered in the course, no experience needed
Windows/MAC computer
What will you learn
You will be able to EXPLAIN, DESIGN and IMPLEMENT efficient java Programs
You will be confident to clear test automation interviews
Understand the concepts of Object Oriented Programming Language
Complete understanding of java
Expert-level knowledge of Java code (+ advanced tips and tricks used by the pros)
Suitable for beginner programmers and ideal for users who learn faster when shown
To learn more: