🧪 EasySale ERP - Test Suite¶
📋 Übersicht¶
Vollständige, skalierbare Test-Architektur für das EasySale ERP Projekt.
🏗️ Struktur¶
test/
├── unit/ # Unit Tests
│ ├── models/ # Model-Tests (Serialisierung, Logik)
│ ├── blocs/ # BLoC-Tests (State Management)
│ ├── services/ # Service-Tests (Business Logic)
│ └── helpers/ # Helper-Tests
│
├── widget/ # Widget Tests
│ ├── pages/ # Seiten-Tests
│ └── components/ # Komponenten-Tests
│
├── integration/ # Integration Tests
│ └── flows/ # End-to-End User Flows
│
├── fixtures/ # Test-Daten (JSON)
│ ├── customer.json
│ ├── article.json
│ └── fixture_reader.dart
│
├── mocks/ # Mock-Klassen
│ ├── mock_firebase.dart # Firebase Mocks
│ └── mock_services.dart # Service Mocks
│
└── helpers/ # Test-Utilities
├── test_helpers.dart # Factory-Methoden
├── firebase_test_setup.dart
├── bloc_test_helpers.dart
└── pump_app.dart # Widget Test Setup
🚀 Quick Start¶
1. Dependencies installieren¶
2. Mocks generieren (optional)¶
Falls du mockito-generierte Mocks verwenden möchtest:
3. Tests ausführen¶
Alle Tests:
Spezifische Test-Datei:
Mit Coverage:
Nur Unit Tests:
Nur Widget Tests:
📚 Test-Typen¶
Unit Tests¶
Testen isolierte Logik ohne Abhängigkeiten:
test('sollte Customer korrekt erstellen', () {
final customer = Customer(
id: 'test-id',
companyName: 'Test GmbH',
customerNumber: 'KUN-123456',
// ...
);
expect(customer.companyName, 'Test GmbH');
});
Was testen: - Models (Serialisierung, copyWith, toMap/fromMap) - Services (Business Logic, Datenverarbeitung) - BLoCs (State Management, Events) - Helper-Funktionen
Widget Tests¶
Testen UI-Komponenten:
testWidgets('sollte Kundendaten anzeigen', (tester) async {
final customer = TestHelpers.createTestCustomer();
await tester.pumpApp(CustomerCard(customer: customer));
expect(find.text(customer.companyName), findsOneWidget);
});
Was testen: - Rendering von Widgets - User-Interaktionen (Tap, Swipe, etc.) - State-Updates in UI - Navigation
Integration Tests¶
Testen komplette User-Flows:
testWidgets('sollte Kunde anlegen können', (tester) async {
// 1. App starten
// 2. Zu Kunden navigieren
// 3. "Neuer Kunde" klicken
// 4. Formular ausfüllen
// 5. Speichern
// 6. Bestätigung prüfen
});
🛠️ Test-Utilities¶
TestHelpers¶
Factory-Methoden für Test-Daten:
// Einzelner Kunde
final customer = TestHelpers.createTestCustomer(
companyName: 'Test GmbH',
customerNumber: 'KUN-123',
);
// Mehrere Kunden
final customers = TestHelpers.createTestCustomers(10);
// Einzelner Artikel
final article = TestHelpers.createTestArticle(
name: 'Test Artikel',
price: 99.99,
);
Fixtures¶
JSON-basierte Test-Daten:
import 'package:test/fixtures/fixture_reader.dart';
// Einzelnes Objekt
final customerMap = mapFixture('customer.json');
final customer = Customer.fromMap('id', customerMap);
// Liste von Objekten
final customersData = listFixture('customers.json');
Mocks¶
Mock-Services für isolierte Tests:
final mockService = MockCustomerService();
mockService.setCustomers(testCustomers);
// Normale Ausführung
final customers = await mockService.getCustomers();
// Error-Simulation
mockService.shouldFail = true;
expect(() => mockService.getCustomers(), throwsException);
Widget Test Helpers¶
Vereinfachtes Widget-Testing:
testWidgets('example', (tester) async {
// Mit vollständigem Material-App Wrapper
await tester.pumpApp(MyWidget());
// Mit Scaffold für Snackbars
await tester.pumpAppWithScaffold(MyWidget());
});
🎯 Best Practices¶
1. AAA-Pattern (Arrange, Act, Assert)¶
test('sollte Preis korrekt berechnen', () {
// Arrange - Setup
final article = Article(price: 100.0);
final quantity = 5;
// Act - Ausführen
final total = article.price * quantity;
// Assert - Überprüfen
expect(total, 500.0);
});
2. Descriptive Test Names¶
✅ Gut: sollte Customer erstellen wenn alle Pflichtfelder vorhanden
❌ Schlecht: test1
3. Unabhängige Tests¶
Jeder Test sollte isoliert laufen können:
setUp(() {
// Setup vor jedem Test
mockService = MockCustomerService();
});
tearDown(() {
// Cleanup nach jedem Test
});
4. Nutze Test-Gruppen¶
group('Customer Model', () {
group('Konstruktor', () {
test('sollte mit Pflichtfeldern erstellen', () { });
});
group('Validierung', () {
test('sollte ungültige Email ablehnen', () { });
});
});
5. Teste Edge Cases¶
test('sollte mit null-Werten umgehen', () { });
test('sollte mit leerer Liste umgehen', () { });
test('sollte bei ungültigen Daten Exception werfen', () { });
🔧 CI/CD Integration¶
GitHub Actions¶
name: Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: subosito/flutter-action@v2
- run: flutter pub get
- run: flutter test
- run: flutter test --coverage
📊 Coverage¶
Ziel: > 80% Code Coverage
Wichtigste Bereiche: - ✅ Models: 100% - ✅ Business Logic: 90%+ - ✅ BLoCs: 80%+ - ⚠️ UI-Widgets: 60%+ (schwerer zu testen)
🐛 Debugging Tests¶
Test einzeln ausführen:¶
flutter test test/unit/models/customer/customer_model_test.dart --plain-name="sollte Customer erstellen"
Verbose Output:¶
Im VSCode:¶
- Öffne Test-Datei
- Klicke auf "Run" über dem Test
- Oder nutze "Debug" für Breakpoints
📝 Nächste Schritte¶
- Erweitere Model-Tests für alle deine Models
- BLoC-Tests für kritische Business Logic
- Service-Tests für Firebase-Integration
- Widget-Tests für wichtige UI-Komponenten
- Integration-Tests für User-Flows
📖 Weitere Ressourcen¶
💡 Tipps¶
Schnellere Tests¶
- Nutze
setUpundtearDownfür Wiederverwendung - Isoliere Firebase-Tests mit Mocks
- Parallele Ausführung mit
--concurrency=4
Wartbare Tests¶
- Nutze
TestHelpersfür konsistente Test-Daten - Zentralisiere Mock-Setup
- Dokumentiere komplexe Test-Szenarien
Debugging¶
- Nutze
printOnFailure()für Debug-Output - Verwende
debugDumpApp()in Widget-Tests - Setze Breakpoints in Debug-Modus
❓ Hilfe¶
Bei Fragen oder Problemen: 1. Schau in die Beispiel-Tests 2. Prüfe die Test-Helpers 3. Konsultiere Flutter Testing Docs
Happy Testing! 🎉
🚀 Quick Start Guide - Testing¶
1️⃣ Setup (einmalig)¶
# Dependencies installieren
flutter pub get
# Optional: Mocks generieren
dart run build_runner build --delete-conflicting-outputs
2️⃣ Ersten Test schreiben¶
Erstelle: test/unit/models/my_model_test.dart
import 'package:flutter_test/flutter_test.dart';
import '../../helpers/test_helpers.dart';
void main() {
group('MyModel', () {
test('sollte korrekt erstellt werden', () {
// Arrange
final model = MyModel(id: '1', name: 'Test');
// Act & Assert
expect(model.name, 'Test');
});
});
}
3️⃣ Test ausführen¶
# Alle Tests
flutter test
# Einzelner Test
flutter test test/unit/models/my_model_test.dart
# Mit Coverage
flutter test --coverage
4️⃣ Test-Struktur erweitern¶
Folge dem Schema:
test/unit/models/[dein_modul]/[dein_model]_test.dart
test/unit/blocs/[dein_bloc]/[dein_bloc]_test.dart
test/unit/services/[dein_service]_test.dart
⚡ Häufige Patterns¶
Model Test¶
test('toMap/fromMap', () {
final model = TestHelpers.createTestCustomer();
final map = model.toMap();
final restored = Customer.fromMap('id', map);
expect(restored.companyName, model.companyName);
});
Service Test mit Mock¶
test('getCustomers', () async {
final mockService = MockCustomerService();
mockService.setCustomers(testData);
final result = await mockService.getCustomers();
expect(result, hasLength(3));
});
Widget Test¶
testWidgets('zeigt Text an', (tester) async {
await tester.pumpApp(Text('Hello'));
expect(find.text('Hello'), findsOneWidget);
});
📖 Mehr Details¶
Siehe test/README.md für vollständige Dokumentation.
🧪 Test Suite Summary - EasySale ERP¶
Status: 351 Tests ✅ | Letzte Aktualisierung: 21. Januar 2026
📊 Test-Abdeckung Übersicht¶
🎯 Gesamt: 351 Tests bestanden¶
| Kategorie | Anzahl | Status |
|---|---|---|
| Unit Tests | 280 | ✅ |
| Service Tests | 10 | ✅ |
| Widget Tests | 43 | ✅ |
| Integration Tests | 18 | ✅ |
📦 Unit Tests (280 Tests)¶
Models (73 Tests)¶
- ✅ Customer Model (11 Tests)
- Constructor, toMap/fromMap, copyWith
- Business Logic (isBlocked, validation)
-
Serialisierung Round-Trip
-
✅ Article Model (11 Tests)
- Serialization, copyWith, validation
- Availability checks, pricing
-
Assignment types (automatic/manual)
-
✅ Order Model (16 Tests)
- OrderPosition creation & calculations
- toMap/fromMap serialization
- copyWith functionality
- Status management & transitions
- Cancellation handling
-
Amount calculations with multiple positions
-
✅ Notification Model (14 Tests)
- Multi-language support (localization)
- Status transitions (notSend → sending → sent)
- Send options (now/planned)
- Customer categories & groups
-
Country filtering
-
✅ CustomerCategory Model (21 Tests)
- Color management (ARGB conversion)
- Icon handling (codePoint)
- Multi-language names
- Serialization round-trip
- Business logic (identifier, updates)
BLoC Logic (207 Tests)¶
- ✅ CustomerBloc (13 Tests)
- SelectCustomer event handling
- CustomersUpdated state management
- Search logic & filtering
- Customer updates & notification groups
-
Business logic (blocked customers, categories)
-
✅ ArticleBloc (20 Tests)
- SelectArticle event handling
- ArticlesUpdated state management
- Search logic (name, number)
- Article updates (price, availability)
- Assignment types (automatic/manual)
-
Business logic (pricing, validation)
-
✅ OrderBloc (20 Tests)
- SelectOrder event handling
- OrdersUpdated state management
- Status transitions (6 states)
- Amount calculations
- Cancellation logic
- Search & filtering
-
Business logic (sorting, validation)
-
✅ NotificationsBloc (16 Tests)
- NotificationsUpdated event handling
- CreateNotification & DeleteNotification
- Notification sorting (newest first)
- Multi-language support
- Send options (now/planned)
- Status management (notSend/sending/sent)
- Customer category & group targeting
- Country filtering
- LoadNotificationCustomerEntries
-
Error tracking
-
✅ AuthBloc (25 Tests)
- State creation & validation (6 states)
- Event creation & property validation
- LoginUser event testing
- LogoutUser event testing
- CheckIfUserIsLoggedIn event
- ResetUserPassword event
- Error state messages (Firebase, network)
- State type hierarchy
-
Event type hierarchy
-
✅ JobBloc (40 Tests)
- JobsLoaded state validation
- Job operations (start, stop, delete, clear)
- Filtering (running, available, system jobs)
- Sorting (recent, alphabetical)
- Schedule management (manual, minutely, hourly, daily, custom)
- Job types (customer, article, order, custom handlers)
- Job history & progress tracking
-
Error handling
-
✅ UsersBloc (35 Tests)
- UsersLoaded state with color getters
- 8 Events (Load, Search, Select, Create, Update, Delete, ResetPassword, Load2FA)
- UserRoleEnum (4 roles)
- LanguageEnum (2 languages)
- User Model validation
- Error states (German messages)
-
Hierarchy validation
-
✅ ConnectorBloc (36 Tests)
- ConnectorsLoaded with source system detection
- 7 Events (Load, Select, Create, Update, Delete, Test, Sync)
- ConnectorType (6 types: database, rest, soap, ftp, email, custom)
- AuthType (5 types: none, basic, bearer, oauth, apiKey)
- DatabaseType (3 types: mysql, postgresql, mssql)
- FieldType (5 types: text, number, date, boolean, list)
- ConnectorConfig model validation
- ScheduleConfig with manual, minutely, hourly, daily, custom
-
Source system detection logic
-
✅ SystemBloc (16 Tests)
- SystemLoaded state validation
- LoadBlocs event testing
- BLoC initialization logic
- State hierarchy validation
- Event hierarchy validation
-
Purpose: Sequential initialization of other BLoCs
-
✅ StatisticBloc (21 Tests)
- StatisticLoaded state with 8 properties
- Cache validation logic (1-hour TTL)
- LoadStatisticsForPeriod event (period, forceReload, autoCheckForUpdates)
- TriggerStatisticsUpdate event
- TimePeriod enum (9 values)
- statistic getter alias
- State & Event hierarchy
- Cache expiration tests (< 1h valid, >= 1h invalid)
- Period statistics for all time ranges
- Credential handling
-
Email format validation
-
🗑️ JobBloc Details - Removed duplicates (Tests now consolidated above in BLoC Logic section)
-
🗑️ UsersBloc Details - Removed duplicates (Tests now consolidated above in BLoC Logic section)
-
🗑️ ConnectorBloc Details - Removed duplicates (Tests now consolidated above in BLoC Logic section)
🔧 Service Tests (10 Tests)¶
- ✅ MockCustomerService (5 Tests)
- getCustomers, getCustomer
-
createCustomer, updateCustomer, deleteCustomer
-
✅ MockArticleService (5 Tests)
- getArticles, getArticle
- createArticle, updateArticle, deleteArticle
🎨 Widget Tests (43 Tests)¶
Example Widget Tests (8 Tests)¶
- ✅ Text display & styling
- ✅ Button interactions & callbacks
- ✅ TextField input handling
- ✅ ListView scrolling & item count
- ✅ Responsive layouts
- ✅ Container with BoxDecoration
- ✅ ListTile in Material context
- ✅ Column layout with children
🔄 Integration Tests (18 Tests)¶
Bestellprozess Flow (7 Tests)¶
- ✅ Kompletter Bestellprozess
- Kunde auswählen → Artikel hinzufügen → Bestellung erstellen
-
Status-Übergänge: Pending → Approved → Processing → Shipped → Delivered
-
✅ Stornierung während Bearbeitung
-
Bestellung genehmigen und dann stornieren
-
✅ Bestellung mit Rabatt
-
Rabattberechnung über mehrere Positionen
-
✅ Mehrere Positionen & Mengen
-
Komplexe Bestellung mit 4+ Positionen
-
✅ Validierung: Gesperrter Kunde
-
Prüfung ob Bestellung verhindert wird
-
✅ Validierung: Nicht verfügbare Artikel
-
Artikel-Verfügbarkeit prüfen
-
✅ Order aktualisieren: Position hinzufügen
- Bestehende Bestellung erweitern
Artikel-Zuweisung Flow (11 Tests)¶
- ✅ Automatische Artikelzuweisung
-
Artikel für alle aktiven Kunden verfügbar
-
✅ Manuelle Artikelzuweisung
-
Artikel nur für spezifische Kunden/Kategorien
-
✅ Filterung nach Verfügbarkeit
-
Nur verfügbare Artikel anzeigen
-
✅ Filterung nach Land
-
Länderspezifische Artikelverfügbarkeit
-
✅ Kompletter Zuweisungs-Flow
-
Artikel → Kategorie → Kunde
-
✅ Artikel-Suche & Filterung
-
Nach Name, Preis, Verfügbarkeit
-
✅ Zuweisung ändern
-
Automatisch → Manuell
-
✅ Verfügbarkeit ändern
-
Artikel aktivieren/deaktivieren
-
✅ Zugriffs-Matrix
-
Mehrere Kunden vs. Artikel-Zugriff
-
✅ Preis-Aktualisierung
-
Preisänderungen für zugewiesene Artikel
-
✅ Bulk-Zuweisung
- Mehrere Artikel gleichzeitig ändern
🚀 Tests ausführen¶
Alle Tests¶
Nach Kategorie¶
# Nur Unit Tests
flutter test test/unit/
# Nur BLoC Tests
flutter test test/unit/blocs/
# Nur Model Tests
flutter test test/unit/models/
# Nur Integration Tests
flutter test test/integration/
# Nur Widget Tests
flutter test test/widget/
Spezifische Tests¶
# Customer Tests
flutter test test/unit/models/customer/
# Order Tests
flutter test test/unit/models/order/
# Auth Tests
flutter test test/unit/blocs/auth_bloc/
# Bestellprozess Integration
flutter test test/integration/order_workflow_test.dart
Mit Code Coverage¶
📝 Test-Struktur¶
test/
├── unit/ # 243 Tests
│ ├── models/ # 73 Tests
│ │ ├── customer/ # 11 Tests
│ │ ├── articles/ # 11 Tests
│ │ ├── order/ # 16 Tests
│ │ ├── notification/ # 14 Tests
│ │ └── customer_category/ # 21 Tests
│ │
│ ├── blocs/ # 170 Tests
│ │ ├── customer_bloc/ # 13 Tests
│ │ ├── article_bloc/ # 20 Tests
│ │ ├── order_bloc/ # 20 Tests
│ │ ├── notification_bloc/ # 16 Tests
│ │ ├── auth_bloc/ # 25 Tests
│ │ ├── job_bloc/ # 40 Tests
│ │ ├── user_bloc/ # 35 Tests
│ │ └── connector_bloc/ # 36 Tests ⭐ NEU
│ │
│ └── services/ # 10 Tests
│ └── mock_services.dart
│
├── widget/ # 43 Tests
│ └── widgets_example_test.dart # 8 Tests
│
├── integration/ # 18 Tests
│ ├── order_workflow_test.dart # 7 Tests
│ └── article_assignment_workflow_test.dart # 11 Tests
│
├── fixtures/ # Test-Daten
│ ├── customer.json
│ ├── article.json
│ ├── order.json
│ ├── notification.json
│ └── customer_category.json
│
├── mocks/ # Mock Services
│ └── mock_services.dart
│
└── helpers/ # Test Utilities
├── test_helpers.dart # Factory Methods
├── fixture_reader.dart # JSON Loader
└── pump_app.dart # Widget Test Setup
🎯 Nächste Schritte¶
Kurzfristig¶
- [x] ~~NotificationBloc Tests (16 Tests)~~ ✅ FERTIG
- [x] ~~AuthBloc Tests (25 Tests)~~ ✅ FERTIG
- [x] ~~JobBloc Tests (40 Tests)~~ ✅ FERTIG
- [x] ~~UsersBloc Tests (35 Tests)~~ ✅ FERTIG
- [x] ~~ConnectorBloc Tests (36 Tests)~~ ✅ FERTIG
- [x] ~~SystemBloc Tests (16 Tests)~~ ✅ FERTIG
- [x] ~~StatisticBloc Tests (21 Tests)~~ ✅ FERTIG
Mittelfristig¶
- [ ] Weitere BLoC Tests (13 verbleibend)
- [ ] ImportBloc
- [ ] ExportBloc
- [ ] CustomerUsersBloc
- [ ] CustomerListsBloc
- [ ] ArticleCategoriesBloc
- [ ] ArticleDocumentBloc
- [ ] TelephonelistsBloc
- [ ] TutorialsBloc
- [ ] DeliveryBreakBloc
- [ ] NavBarBloc
- [ ] SystemSettingsBloc
- [ ] ArticlePackageSizesBloc
- [ ] NotificationGroupsBloc
- [ ] Weitere Integration Flows
- [ ] Import-Workflow
- [ ] Export-Workflow
- [ ] Statistik-Berechnung
Langfristig¶
- [ ] E2E Tests mit echten Firebase Emulators
- [ ] Performance Tests
- [ ] Golden Tests für kritische UI-Komponenten
- [ ] Code Coverage > 80%
📚 Weitere Dokumentation¶
- test/README.md - Vollständige Test-Dokumentation
- test/helpers/test_helpers.dart - Factory-Methoden
Status: Produktionsbereit ✅
Maintainer: Development Team
Letzte große Änderung: 21. Januar 2026