Let’s talk serialization. In APIs and testing context, naturally.

Serialization is a technique of taking an object and dumping it into a stream. It could be a stream of bytes, zeros and ones. But in the API world, we usually serialize objects into JSON or XML.

Here’s an example of a Java object:

public class User{
    public String name;
    public int age;
    public boolean isStudent;
}Code language: Java (java)

And the serialized version:

{
  "User": {
            name: "Joe",
            age: 32,
            isStudent: false
          }
}Code language: JSON / JSON with Comments (json)

Deserialization is the opposite – taking that stream, or JSON in our case, and building an object out of its values.

I can send that JSON as a request body from a Javascript front-end, for example, to a Java server:

@PostMapping(value = "/add", consumes = MediaType.APPLICATION_JSON_VALUE)
public void addUser(@RequestBody User theUser){
  ...
}Code language: Java (java)

As you can see (or not, in this case), serialization is invisible. But it happens, through the Spring runtime that knows how to serialize a sent object as a JSON body. It also does the same with outgoing response body.
Developers are starting from objects and returning objects, and don’t need any mapping, serializing or deserializing themselves.

Which is cool, unless there’s a problem.

Since the HTTP request is sent with a JSON content, it is basically a string. This string can be anything. It can be:

  • Empty
  • Invalid JSON (e.g. no matching braces)
  • Different version of JSON (e.g. same object, but with an extra field)
  • Completely different JSON (e.g. the wrong object)

When the JSON arrives at the other end, it will be translated automatically, and fail. But because we rely on translation magic, we won’t see where it happens. It will be in either before or after the controller’s method. In our case, it’s a request body, so in the “before”.

Ok, so what?

As a back-end developer, my life is easier because of the automatic serialization, but debugging becomes harder.

As a front-end developer, I need to know exactly what to send – object, structure and version – so there won’t be any problem.

As a tester, life becomes very interesting. Because if I test APIs, I can send all kinds of inputs, and see how the system behaves.

I can even send:

“DROP TABLE Users”

And have a good laugh (hopefully not).

Understanding serialization is important, because it helps to uncover and solve problems, that otherwise will be shot down with “It’s not my code”. We need to understand how serialization works and how to identify problems when it fails. And we need to understand it takes place so we can test it.

And lucky for you, I do a whole workshop for API developer tests. Check it out.

Categories: Uncategorized

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *