---
title: "Use Map and JSON.serialize to mock HTTP Response"
url: "https://blog.beyondthecloud.dev/tips/use-map-and-json-serialize-to-mock-http-response"
category: "Testing"
published: "2024-01-02"
---

# Use Map and JSON.serialize to mock HTTP Response

Since the HTTP Body is a JSON, in this way, the code is as much similar/formatted as standard JSON as possible.

### Use Map and JSON.serialize to mock HTTP Response

Did you ever try to mock an HTTP response?

Perhaps you did something like this:

```apex
HttpResponse response = new HttpResponse();
response.setHeader('Content-Type', 'application/json');
response.setBody('{"name":"my_username", "first-name": "My", "email": "user" + UserInfo.getUserId() +
    "@example.test", "attributes": { "rel": "edit" }}');
response.setStatusCode(200);
return response;
```

This is the most common approach, but...

You can make it cleaner with Map and JSON.serialize.

```apex
HttpResponse response = new HttpResponse();
response.setHeader('Content-Type', 'application/json');
response.setBody(JSON.serialize(
    new Map<String, Object>{
        'name' => 'my_username',
        'first-name' => 'My',
        'email' => 'user' + UserInfo.getUserId() + '@example.test',
        'attributes' => new Map<String, Object>{
            'rel' => 'edit'
        }
    }
));
response.setStatusCode(200);
return response;
```

Since the HTTP Body is a JSON, in this way, the code is as much similar/formatted as standard JSON as possible.

There is no need to create wrappers. Just a simple Map, JSON.serialize, and voilà!
