Integration testing checks if different parts of a program work well together. It helps find problems when pieces connect.
Integration testing in Rest API
def test_api_integration(): response = client.get('/api/resource') assert response.status_code == 200 assert 'expected_key' in response.json()
This example shows a simple integration test for a REST API endpoint.
Use a test client to send requests and check responses.
def test_get_user(): response = client.get('/users/1') assert response.status_code == 200 assert response.json()['id'] == 1
def test_create_post(): data = {'title': 'Hello', 'content': 'World'} response = client.post('/posts', json=data) assert response.status_code == 201 assert response.json()['title'] == 'Hello'
This program creates a simple API with two endpoints: one to add posts and one to get all posts. The test sends a post, then checks if it was saved and can be retrieved.
from fastapi import FastAPI from fastapi.testclient import TestClient app = FastAPI() posts = [] @app.post('/posts') def create_post(post: dict): posts.append(post) return post @app.get('/posts') def get_posts(): return posts client = TestClient(app) def test_create_and_get_posts(): new_post = {'title': 'Test', 'content': 'Integration'} response = client.post('/posts', json=new_post) assert response.status_code == 201 assert response.json() == new_post response = client.get('/posts') assert response.status_code == 200 assert new_post in response.json() if __name__ == '__main__': test_create_and_get_posts() print('Integration test passed')
Integration tests are slower than unit tests because they test multiple parts together.
Keep integration tests focused on how parts work together, not on internal details.
Use test databases or mock services to avoid changing real data.
Integration testing checks if different parts of your app work together correctly.
It is useful for testing API endpoints, databases, and service communication.
Write tests that send requests and check responses to catch connection problems early.