Best practises
Imports
While it's possible to import types and test helpers from the serverpod_test
, it's completely redundant. The generated file exports everything that is needed. Adding an additional import is just unnecessary noise and will likely also be flagged as duplicated imports by the Dart linter.
Don't
import 'serverpod_test_tools.dart';
// Don't import `serverpod_test` directly.
import 'package:serverpod_test/serverpod_test.dart'; ❌
Do
// Only import the generated test tools file.
// It re-exports all helpers and types that are needed.
import 'serverpod_test_tools.dart'; ✅
Database clean up
Unless configured otherwise, by default withServerpod
does all database operations inside a transaction that is rolled back after each test
(see the configuration options for more info on this behavior).
Don't
withServerpod('Given ProductsEndpoint', (sessionBuilder, endpoints) {
var session = sessionBuilder.build();
setUp(() async {
await Product.db.insertRow(session, Product(name: 'Apple', price: 10));
});
tearDown(() async {
await Product.db.deleteWhere( ❌ // Unnecessary clean up
session,
where: (_) => Constant.bool(true),
);
});
// ...
});
Do
withServerpod('Given ProductsEndpoint', (sessionBuilder, endpoints) {
var session = sessionBuilder.build();
setUp(() async {
await Product.db.insertRow(session, Product(name: 'Apple', price: 10));
});
✅ // Clean up can be omitted since the transaction is rolled back after each by default
// ...
});