Isaac.

Implement Unit Tests and Integration Tests

Introduction

Testing is a critical part of software development. Unit tests validate individual components of your application, while integration tests ensure different components work together correctly. Ignoring testing can lead to bugs in production, unstable features, and decreased developer confidence.

Unit Testing

Unit tests focus on isolated parts of your application, typically a single function or class. They are fast to run and help catch regressions early.

Integration Testing

Integration tests verify that different modules or services interact as expected. They are essential for testing real-world workflows and data interactions.

Examples Across Platforms

ASP.NET Core

Unit test using xUnit for a simple Calculator service:

public class Calculator
{
    public int Add(int a, int b) => a + b;
}

public class CalculatorTests
{
    [Fact]
    public void Add_ReturnsCorrectSum()
    {
        var calc = new Calculator();
        var result = calc.Add(2, 3);
        Assert.Equal(5, result);
    }
}

Integration test using WebApplicationFactory:

public class ApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public ApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetEndpoint_ReturnsSuccess()
    {
        var response = await _client.GetAsync("/api/values");
        response.EnsureSuccessStatusCode();
        var content = await response.Content.ReadAsStringAsync();
        Assert.Contains("value1", content);
    }
}

Spring Boot

Unit test for a service:

@Service
public class CalculatorService {
    public int add(int a, int b) {
        return a + b;
    }
}

@SpringBootTest
public class CalculatorServiceTest {
    @Autowired
    CalculatorService service;

    @Test
    void testAdd() {
        assertEquals(5, service.add(2, 3));
    }
}

Express.js

Unit test using Jest:

// sum.js
function sum(a, b) {
  return a + b;
}
module.exports = sum;

// sum.test.js
const sum = require('./sum');

test('adds 2 + 3 to equal 5', () => {
  expect(sum(2, 3)).toBe(5);
});

Next.js

Unit test using React Testing Library:

import { render, screen } from '@testing-library/react';
import Button from '../components/Button';

test('renders button with text', () => {
  render(<Button>Click me</Button>);
  expect(screen.getByText('Click me')).toBeInTheDocument();
});

Flask

Integration test using Flask test client:

from flask import Flask
import unittest

app = Flask(__name__)

@app.route("/hello")
def hello():
    return "Hello World"

class FlaskTestCase(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()

    def test_hello(self):
        response = self.app.get('/hello')
        self.assertEqual(response.data, b'Hello World')

if __name__ == "__main__":
    unittest.main()

Laravel

Unit test using PHPUnit:

// app/Services/Calculator.php
namespace App\Services;
class Calculator {
    public function add($a, $b) { return $a + $b; }
}

// tests/Unit/CalculatorTest.php
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
use App\ServicesCalculator;

class CalculatorTest extends TestCase {
    public function testAdd() {
        $calc = new Calculator();
        $this->assertEquals(5, $calc->add(2, 3));
    }
}

Conclusion

Implementing unit and integration tests is essential for building reliable software. Unit tests help identify bugs early, while integration tests ensure your application components work together as expected. Ignoring testing can lead to production failures, increased maintenance costs, and slower development cycles.

Key Takeaways:

  • Unit tests validate individual pieces of logic quickly.
  • Integration tests validate end-to-end workflows.
  • ASP.NET offers strong tools like xUnit and WebApplicationFactory for testing.
  • Testing across different frameworks ensures consistency and reliability.