Automated Testing (Unit and Integration)
Unit Testing
Frameworks
- Go: The Go programming language provides a built-in testing framework.
- xUnit: A popular framework that supports a wide range of languages, including Python, Java, C++, and more.
Examples
Go
package main
import "testing"
func TestAdd(t *testing.T) {
result := add(2, 3)
if result != 5 {
t.Errorf("Expected 5, got %d", result)
}
}
xUnit (Python)
import unittest
class TestAdd(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
Best Practices
- Isolate tests: Each test should focus on a single unit of code.
- Use assertions: Assertions help to verify the expected behavior of the code.
- Keep tests concise: Short, focused tests are easier to understand and maintain.
- Cover all code paths: Aim for a high test coverage to ensure all functionality is tested.
Integration Testing
Frameworks
- Go: Similar to unit testing, the Go standard library provides support for integration testing.
- Selenium: A popular framework for testing web applications.
Examples
Go
package main
import (
"testing"
"net/http"
)
func TestServer(t *testing.T) {
server := createServer()
defer server.Close()
resp, err := http.Get("http://localhost:8080")
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status code 200, got %d", resp.StatusCode)
}
}
Best Practices
- Test interactions between components: Integration tests verify how different parts of the system work together.
- Use mock objects: Mock objects can simulate dependencies to simplify integration tests.
- Focus on realistic scenarios: Tests should reflect how the application is expected to be used.
- Use a test environment: A dedicated testing environment helps to isolate tests from the production environment.