Skip to content

Commit 0a9d1a2

Browse files
committed
feat: Add testing contribution guideline
1 parent 8c2b1b7 commit 0a9d1a2

File tree

1 file changed

+258
-0
lines changed

1 file changed

+258
-0
lines changed
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
# Serverpod Testing Philosophy
2+
3+
## Overview
4+
5+
At Serverpod, our core testing philosophy revolves around achieving the following goals:
6+
7+
- **Readable and Self-Explanatory Tests** – Tests should be easy to understand at a glance. Descriptions must clearly convey the purpose and expected outcome without needing to inspect the test's internal implementation.
8+
- **Resilient to Refactoring** – Tests should not break due to internal refactoring. As long as the external behavior remains consistent, tests should pass regardless of code structure changes.
9+
- **Focused on Behavior, Not Implementation** – We prioritize testing how the code behaves rather than how it is implemented. This prevents unnecessary coupling between tests and production code, fostering long-term stability.
10+
- **Easy to Maintain and Expand** – Tests should be simple to update or extend as the product evolves. Adding new features should not require widespread changes to existing tests.
11+
- **Effective at Catching Bugs** – The primary goal of testing is to identify and prevent bugs. Our tests are crafted to cover edge cases, ensure proper functionality, and catch potential regressions.
12+
13+
By adhering to the following principles, we ensure that our test suite remains a valuable and reliable asset as our codebase grows.
14+
15+
This document outlines Serverpod's approach to testing code. It serves as a guide for writing effective, maintainable, and meaningful tests across all our projects.
16+
17+
## Key Principles
18+
19+
### 0. Test Independence
20+
21+
- **Tests should be completely independent of one another.**
22+
- The outcome of a test must never depend on any other test running before or after it.
23+
- The order in which tests are executed **should not matter.**
24+
- Running a single test in isolation must produce the same result as running it alongside others.
25+
- **Exception to the rule:** e2e and integration tests. In scenarios where an external state (like a shared database) is involved, tests may require concurrency mode 1 to prevent interference. But each test should start and end in a clean state.
26+
27+
### 1. Clear and Descriptive Test Descriptions
28+
29+
- **Test descriptions should be understandable without reading the test code.**
30+
- If a test fails, the description alone should make it clear what went wrong.
31+
- **Format:** Descriptions follow the "Given, When, Then" style.
32+
33+
**Example:**
34+
35+
```dart
36+
// Given a user with insufficient permissions
37+
// When attempting to access a restricted page
38+
// Then a 403 Forbidden error is returned
39+
```
40+
41+
### 2. Focus on Single Responsibility
42+
43+
- Each test should **only test one thing**.
44+
- **Avoid** bundling multiple independent checks into a single test.
45+
- It is acceptable to **repeat the same precondition and action** across tests to ensure each aspect is tested individually.
46+
47+
**Example:**
48+
49+
```dart
50+
// Good - Tests are split
51+
test('Given an empty list when a string is added then it appears at the first index', () {
52+
final list = [];
53+
list.add('hello');
54+
expect(list[0], 'hello');
55+
});
56+
57+
test('Given an empty list when a string is added then list length increases by one', () {
58+
final list = [];
59+
list.add('hello');
60+
expect(list.length, 1);
61+
});
62+
63+
// Bad - Multiple independent checks in one test
64+
test('Add string to list and check index and length', () {
65+
final list = [];
66+
list.add('hello');
67+
expect(list[0], 'hello');
68+
expect(list.length, 1);
69+
});
70+
```
71+
72+
- Multiple `expect` statements are not necessarily against this rule. However, they must check values that are interdependent and only meaningful when evaluated together.
73+
74+
**Example:**
75+
76+
```dart
77+
test('Given a missing semicolon when validated then the entire row is highlighted', () {
78+
final code = 'final a = 1';
79+
final result = validateCode(code);
80+
81+
expect(result.span.start.column, 1);
82+
expect(result.span.end.column, 12);
83+
expect(result.span.start.line, 1);
84+
expect(result.span.end.line, 1);
85+
});
86+
```
87+
88+
- In this case, verifying both the start and end positions of the `SourceSpanException` is essential because they collectively describe the error location, and their correctness is interdependent.
89+
90+
\*Note: SourceSpanException is an object that describes a code error in a source file. See: \*[*https://api.flutter.dev/flutter/package-source\_span\_source\_span/SourceSpanException-class.html*](https://api.flutter.dev/flutter/package-source_span_source_span/SourceSpanException-class.html) 
91+
92+
### 3. Pure Unit Testing
93+
94+
- **Unit tests should avoid mocking and side effects.**
95+
- Production code should push side effects **up the call stack**, allowing tests to cover pure methods.
96+
- **Test the logical feature/unit** rather than a single method or class.
97+
98+
**Example:**
99+
100+
```dart
101+
// Avoid mocking HTTP requests directly, test the logic that processes the response
102+
Future<String> fetchUserData() async {
103+
final response = await httpClient.get(url);
104+
return processResponse(response);
105+
}
106+
```
107+
108+
- Test `processResponse` directly without mocking the `httpClient`.
109+
110+
### 4. Implementation-Agnostic Tests
111+
112+
- **Do not couple tests to implementation details.**
113+
- Tests should only break if the behavior changes, not when refactoring code.
114+
- **Unit tests must avoid knowledge of internal methods or variables.**
115+
- The use of `@visibleForTesting` is discouraged as it exposes internal details that should remain hidden. This annotation can lead to brittle tests that break during refactoring, even if external behavior remains the same.
116+
117+
**Example:**
118+
119+
```dart
120+
// Good - Tests against behavior
121+
String processUserData(String rawData) {
122+
return rawData.toUpperCase();
123+
}
124+
125+
test('Given a user name when processed then the name is capitalized', () {
126+
final result = processUserData('john');
127+
expect(result, 'JOHN');
128+
});
129+
130+
// Bad - Tests against internal methods or state
131+
class UserDataProcessor {
132+
String process(String rawData) {
133+
return _toUpperCase(rawData);
134+
}
135+
136+
@visibleForTesting
137+
String toUpperCase(String input) => input.toUpperCase();
138+
}
139+
140+
// Bad - Verifying internal method call
141+
test('Given a user name when processed then toUpperCase is called', () {
142+
final processor = UserDataProcessor();
143+
144+
when(() => processor.toUpperCase('john')).thenReturn('JOHN');
145+
146+
final result = processor.process('john');
147+
148+
expect(result, 'JOHN');
149+
verify(() => processor.toUpperCase('john')).called(1);
150+
});
151+
```
152+
153+
- In the bad example, the test verifies that an internal method (`_toUpperCase`) is called, coupling the test to the implementation. The good example validates only the output, ensuring the test focuses on behavior rather than internal details.
154+
155+
### 5. Immutable Test Philosophy
156+
157+
- **Tests should rarely be modified.**
158+
- When functionality changes, **add new tests** and/or **remove obsolete ones**.
159+
- Avoid altering existing tests unless fixing bugs, e.g. invalid tests.
160+
161+
### 6. Simplicity Over Abstraction
162+
163+
- The explicit examples make it clear what is being tested and reduce the need to jump between methods. The abstracted logic example hides test behavior, making it harder to understand specific test scenarios at a glance.
164+
- **Avoid abstraction in tests.**
165+
- Tests should be **simple, explicit, and easy to read.**
166+
- Logic or shared test functionality should be **copied** rather than abstracted.
167+
168+
**Examples:**
169+
170+
```dart
171+
// Good - Explicit test
172+
test('Given a number below threshold when validated then an error is collected', () {
173+
final result = validateNumber(3);
174+
175+
expect(result.errors.first.message, 'Number must be 5 or greater.');
176+
});
177+
178+
// Good - Explicit test for out of range value
179+
test('Given a number above range when validated then range error is collected', () {
180+
final result = validateNumber(11);
181+
182+
expect(result.errors.first.message, 'Number must not exceed 10.');
183+
});
184+
185+
// Bad - Abstracted logic into a method
186+
void performValidationTest(int number, String expectedErrorMessage) {
187+
final result = validateNumber(number);
188+
189+
expect(result.errors.first.message, expectedErrorMessage);
190+
}
191+
192+
test('Number below threshold', () {
193+
performValidationTest(3, 'Number must be 5 or greater.');
194+
});
195+
196+
test('Number above range', () {
197+
performValidationTest(11, 'Number must not exceed 10.');
198+
});
199+
```
200+
201+
### 7. Beneficial Abstractions - Test Builders
202+
203+
- One abstraction we encourage is the **test builder pattern** for constructing test input objects.
204+
- Builders help create logical, valid objects while keeping tests simple and readable.
205+
206+
**Key Characteristics:**
207+
208+
- Builder class names follow the pattern: `ObjectNameBuilder`.
209+
- Methods that set properties start with `with`, and return the builder instance (`this`).
210+
- Builders always include a `build` method that returns the final constructed object.
211+
- Constructors provide reasonable defaults for all properties to ensure valid object creation by default.
212+
213+
**Guidelines:**
214+
215+
- In tests, always set the properties that are important for the specific scenario.
216+
- Defaults allow seamless addition of new properties without modifying existing tests.
217+
- Using builders ensures objects are created in a realistic, lifecycle-accurate way.
218+
219+
**Example:**
220+
221+
```dart
222+
class UserBuilder {
223+
String _name = 'John Doe';
224+
int _age = 25;
225+
226+
UserBuilder withName(String name) {
227+
_name = name;
228+
return this;
229+
}
230+
231+
UserBuilder withAge(int age) {
232+
_age = age;
233+
return this;
234+
}
235+
236+
User build() {
237+
return User(name: _name, age: _age);
238+
}
239+
}
240+
241+
// Test Example
242+
test('Given a user at the legal cut of when checking if they are allowed to drink then they are', () {
243+
final user = UserBuilder().withAge(18).build();
244+
final isAllowed = isLegalDrinkingAge(user);
245+
expect(isAllowed, isTrue);
246+
});
247+
```
248+
249+
- **Benefits:**
250+
- Reduces test brittleness when refactoring.
251+
- Ensures tests continue to produce valid objects as the code evolves.
252+
- Simplifies object creation without requiring deep lifecycle knowledge.
253+
254+
## Final Thoughts
255+
256+
Consistent application of these principles leads to a robust and maintainable codebase, fostering confidence in our product's reliability and scalability.
257+
258+
We acknowledge that there are exceptions to the rules. But when deviating from the guidelines mentioned above you have to argue for why. You must have a reasonable argument that aligns with the core goals.

0 commit comments

Comments
 (0)