DEV Community

Cover image for How to easily test REST endpoints in Laravel with minimal syntax.
Chris Arter
Chris Arter

Posted on

How to easily test REST endpoints in Laravel with minimal syntax.

When I write unit tests for APIs, I try to write tests that are as flexible and durable as possible. I try my best to avoid brittle tests that may break if some implementation in my code base should change.

Ideally, tests should not care at all about the implementation, and only care that with X input, we get Y output. Some of your endpoints may return Laravel API Resources. I've seen some developers write tests that ensure that the resource is returned compared to a given shape / array. But, we don't really care about that, do we? We may change our API Resource class, but we want our test to stay resilient.

In the example image above, we'll say we only really care that the title and content of a post is included in the API response. Other fields may change in our resource, but this test ensures that those two fields are always contained in the response.

This is best achieved by using assertJsonFragment. You may have used assertJson() before, but since we are interested in creating as durable tests as possible, assertJsonFragment ensures the tests won't fail if the shape of our returned response changes.

Continue reading

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (1)

Collapse
 
amitavroy7 profile image
Amitav Roy

Yeah, testing on Laravel is fun with the small small but very powerful functions that are available.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay