# BuyerKiosk Live - Testing Documentation

Complete testing guide and resources for Flutter 3.38.3 with Riverpod 3.x and Mocktail.

## Documentation Files

### Start Here

1. **[TESTING_SUMMARY.md](./TESTING_SUMMARY.md)** (Research Report)
   - Executive summary of testing best practices for 2025
   - Key findings and recommendations
   - Implementation roadmap (5-week plan)
   - Common pitfalls and solutions
   - **Read time:** 15 minutes
   - **Best for:** Understanding the big picture and getting buy-in

2. **[TESTING_GUIDE.md](./TESTING_GUIDE.md)** (Comprehensive Guide)
   - 11 detailed sections covering all testing scenarios
   - Code examples for every pattern
   - Riverpod 3.x AsyncNotifier testing deep dive
   - GoRouter navigation testing patterns
   - Coverage setup with GitHub Actions
   - **Read time:** 45 minutes
   - **Best for:** Learning detailed patterns and implementation

3. **[TESTING_CHEAT_SHEET.md](./TESTING_CHEAT_SHEET.md)** (Quick Reference)
   - Command cheat sheet
   - Common test patterns (copy-paste ready)
   - Mocktail quick reference
   - Debugging commands
   - **Read time:** 5 minutes
   - **Best for:** Quick lookups during coding

---

## Example Test Files

### 1. Provider Testing Example
**File:** `test/presentation/providers/dashboard_provider_test_example.dart`

Shows how to test AsyncNotifier providers with:
- Basic data loading
- Error handling
- Provider refresh
- Listener verification
- Family providers (with parameters)

**Study this first.** Copy the patterns to your other provider tests.

### 2. Widget Testing Example
**File:** `test/presentation/screens/dashboard_screen_test_example.dart`

Shows how to test screens with:
- Data display
- Loading/error/empty states
- User interactions (taps, scrolls, input)
- Navigation with mocked GoRouter
- Pull-to-refresh functionality

**Study this after providers.** Apply these patterns to all your screens.

### 3. Integration Testing Example
**File:** `test/integration/auth_flow_integration_test_example.dart`

Shows how to test complete user journeys:
- Authentication flow
- Multi-screen navigation
- Real API calls (not mocked)
- Error recovery
- Permission-based access

**Study this last.** Use selectively for critical user flows only.

---

## Fixture & Setup Files

### Mock Factories
**File:** `test/fixtures/test_mocks.dart`

Pre-built mocks and utilities:
- `MockStoreRepository`, `MockWorkbookNoteRepository`, etc.
- `registerFallbackValues()` - One-call setup for all types
- Stubbing helpers with extension methods
- Test data factories
- Verification helpers

**Usage:**
```dart
import 'test/fixtures/test_mocks.dart';

void main() {
  group('MyTest', () {
    late MockStoreRepository mockRepo;

    setUpAll(() {
      registerFallbackValues(); // One line!
    });

    setUp(() {
      mockRepo = MockStoreRepository();
    });

    test('test name', () {
      mockRepo.stubGetAllStoresSuccess(testStores);
      // ...
    });
  });
}
```

---

## CI/CD Setup

### GitHub Actions Workflow
**File:** `.github/workflows/test.yml`

Automated testing on every push/PR:
- Runs tests with coverage
- Uploads to Codecov
- Enforces minimum coverage (70%)
- Linting checks
- Security scanning
- Generates artifacts

**Status:** Ready to use. Just add repo to Codecov.

---

## Getting Started: 5-Minute Setup

### 1. Update `pubspec.yaml`
You already have `mocktail: ^1.0.3`, which is all you need for mocking.

### 2. Create Test Directory Structure
```bash
mkdir -p test/fixtures test/helpers test/presentation/providers test/presentation/screens test/domain test/integration
```

### 3. Copy Fixture File
```bash
cp test/fixtures/test_mocks.dart test/fixtures/
```

### 4. Review Example Tests
- Open `test/presentation/providers/dashboard_provider_test_example.dart`
- Read the comments explaining each pattern
- Copy to `test/presentation/providers/my_provider_test.dart`

### 5. Run First Test
```bash
flutter test test/presentation/providers/dashboard_provider_test_example.dart
```

---

## Test Writing Workflow

### Step 1: Understand the Code
- What does the provider/screen do?
- What are all possible states? (loading, success, error, empty)
- What are the inputs and outputs?

### Step 2: Set Up Mocks
```dart
late MockStoreRepository mockRepo;

setUpAll(() {
  registerFallbackValues();
});

setUp(() {
  mockRepo = MockStoreRepository();
});
```

### Step 3: Write Test Following Arrange-Act-Assert
```dart
test('loads data successfully', () async {
  // ARRANGE
  when(() => mockRepo.getData())
      .thenAnswer((_) async => testData);

  final container = ProviderContainer(
    overrides: [repositoryProvider.overrideWithValue(mockRepo)],
  );
  addTearDown(container.dispose);

  // ACT
  final listener = Listener<AsyncValue<List<MyType>>>();
  container.listen(myProvider, listener);
  await Future<void>.value();
  await container.pump();

  // ASSERT
  expect(container.read(myProvider).value, equals(testData));
});
```

### Step 4: Add More Test Cases
- Test each state (loading, success, error, empty)
- Test edge cases
- Test user interactions

### Step 5: Run & Verify
```bash
flutter test test/my_test.dart -v
```

---

## Testing Checklist

### Before Writing Code
- [ ] Have you reviewed the example tests?
- [ ] Do you understand the Arrange-Act-Assert pattern?
- [ ] Have you identified all possible states?

### While Writing Tests
- [ ] One behavior per test
- [ ] Clear test names describing behavior
- [ ] Mocks configured with `when(...).thenAnswer(...)`
- [ ] Container disposed with `addTearDown(container.dispose)`
- [ ] Async operations awaited properly
- [ ] Assertions verify behavior, not implementation

### Before Merging PR
- [ ] All tests pass: `flutter test`
- [ ] No test files with `.only` or `.skip`
- [ ] Coverage maintained/improved (70%+)
- [ ] No hardcoded delays or `sleep()`
- [ ] GoRouter mocked or properly configured

### Before Release
- [ ] Coverage at least 70%: `flutter test --coverage`
- [ ] Integration tests for critical flows
- [ ] No flaky tests (run tests 10x)

---

## Command Reference

```bash
# Run all tests
flutter test

# Run specific file
flutter test test/domain/repositories/store_repository_test.dart

# Run tests matching pattern
flutter test -k "dashboard"

# Watch mode (rerun on file changes)
flutter test --watch

# Run with coverage
flutter test --coverage

# Run in parallel (faster)
flutter test --concurrency=4

# Run serially for debugging
flutter test --concurrency=1

# Generate HTML coverage report
flutter test --coverage && genhtml coverage/lcov.info -o coverage/html && open coverage/html/index.html

# Run integration tests
flutter test integration_test/ -d <device_id>

# Clean and rebuild
flutter clean && flutter pub get && dart run build_runner build
```

---

## Common Issues & Solutions

### "Container not disposed"
```dart
✅ final container = ProviderContainer();
✅ addTearDown(container.dispose);
```

### "Listener only called once"
```dart
✅ await Future<void>.value();  // Pump microtasks
✅ await container.pump();      // Pump async operations
```

### "No GoRouter found in context"
```dart
✅ TestApp(
  overrides: [goRouterProvider.overrideWithValue(mockRouter)],
)
```

### "AsyncLoading != AsyncLoading"
```dart
❌ expect(state, equals(AsyncLoading()));

✅ verify(() => listener(any(), any(that: isA<AsyncLoading>())))
    .called(1);
```

### "Widget not found after async"
```dart
❌ await tester.pump();

✅ await tester.pumpAndSettle();  // Waits for animations
```

See **[TESTING_GUIDE.md](./TESTING_GUIDE.md)** section 8 for more issues & solutions.

---

## Coverage Targets

| Phase | Target | Notes |
|-------|--------|-------|
| Week 1 | 40% | Foundation (fixtures, examples) |
| Week 2 | 50% | Providers tested |
| Week 3 | 60% | Main screens tested |
| Week 4 | 70% | Edge cases, error handling |
| Month 2+ | 75%+ | Continuous improvement |

**Generate Coverage Report:**
```bash
flutter test --coverage
genhtml coverage/lcov.info -o coverage/html
open coverage/html/index.html
```

---

## Integration with CI/CD

The `.github/workflows/test.yml` file is ready to use. It will:

1. Run tests on every push to `main` or `develop`
2. Run tests on every pull request
3. Upload coverage to Codecov
4. Enforce 70% minimum coverage
5. Generate coverage report as artifact

**Setup:**
1. Commit `.github/workflows/test.yml`
2. Push to GitHub
3. Register repo at [codecov.io](https://codecov.io)
4. Tests will automatically run

---

## Testing Best Practices Summary

### Testing Pyramid
- **50-60%** Unit Tests (providers, mappers, utilities)
- **30-35%** Widget Tests (screens, user interactions)
- **5-10%** Integration Tests (critical user journeys)

### Key Patterns
1. **Unit:** `ProviderContainer` + `Listener` verification
2. **Widget:** Override providers, mock GoRouter, test interactions
3. **Integration:** Real API calls, complete user flows

### Golden Rules
1. Always dispose containers: `addTearDown(container.dispose)`
2. Use listeners for AsyncValue: `container.listen(provider, listener)`
3. Await properly: `await Future<void>.value(); await container.pump();`
4. One thing per test: One behavior, one assertion per test
5. Use fixtures: Centralize test data
6. Mock dependencies: Isolate code under test

---

## Resources

### Official Documentation
- [Flutter Testing Overview](https://docs.flutter.dev/testing/overview)
- [Riverpod Testing Guide](https://riverpod.dev/docs/essentials/testing)
- [Mocktail Package](https://pub.dev/packages/mocktail)
- [GoRouter Testing](https://guillaume.bernos.dev/testing-go-router/)

### Community Resources
- [Code with Andrea: AsyncNotifier Testing](https://codewithandrea.com/articles/unit-test-async-notifier-riverpod/)
- [Code with Andrea: Test Coverage](https://codewithandrea.com/articles/flutter-test-coverage/)

### Your Project Documentation
- `/CLAUDE.md` - Project architecture overview
- `/TESTING_GUIDE.md` - Comprehensive testing guide
- `/TESTING_SUMMARY.md` - Research report with findings
- `/TESTING_CHEAT_SHEET.md` - Quick reference

---

## FAQ

### Q: Do I need to test everything?
**A:** No. Focus on:
- Business logic (providers, repositories)
- User interactions (screens)
- Critical flows (integration tests)
- Error cases

### Q: Should I use real API or mock?
**A:** Mock for unit/widget tests (fast, isolated). Real API for integration tests (realistic).

### Q: How much coverage do I need?
**A:** Target 70%+ for production code. Aim for quality over quantity - test critical paths, not trivial setters.

### Q: Why use Mocktail over Mockito?
**A:** Simpler setup (no code generation), Dart-first design, better for Riverpod ecosystem.

### Q: Can I run integration tests in CI/CD?
**A:** Yes, but they're slower. Use GitHub Actions + Android/iOS runners. Example provided in `.github/workflows/test.yml`.

### Q: What if tests pass locally but fail in CI?
**A:** Run tests serially locally: `flutter test --concurrency=1`. Check for timing issues or environment differences.

---

## Next Steps

1. **Read:** [TESTING_SUMMARY.md](./TESTING_SUMMARY.md) (15 min)
2. **Review:** Example test files (30 min)
   - `test/presentation/providers/dashboard_provider_test_example.dart`
   - `test/presentation/screens/dashboard_screen_test_example.dart`
3. **Setup:** Copy `test/fixtures/test_mocks.dart` (5 min)
4. **Write:** First provider test using example as template (30 min)
5. **Run:** `flutter test` and verify it passes (5 min)
6. **Expand:** Write tests for remaining providers (1-2 weeks)
7. **Scale:** Add screen tests and integration tests (2-4 weeks)
8. **Monitor:** Track coverage growth toward 70%+ (ongoing)

---

## Support

### Troubleshooting
1. Check [TESTING_GUIDE.md](./TESTING_GUIDE.md) section 8 - Common Issues
2. Check [TESTING_CHEAT_SHEET.md](./TESTING_CHEAT_SHEET.md) - Quick patterns
3. Review example files for working code patterns

### Questions
- See `TESTING_SUMMARY.md` for research findings
- See `TESTING_GUIDE.md` for detailed explanations
- See example files for working code

---

## File Organization

```
buyerkiosk-live-flutter/
├── TESTING_README.md                      ← You are here
├── TESTING_SUMMARY.md                     (Research, roadmap)
├── TESTING_GUIDE.md                       (Comprehensive guide)
├── TESTING_CHEAT_SHEET.md                 (Quick reference)
│
├── test/
│   ├── fixtures/
│   │   └── test_mocks.dart                (Mock factories, utils)
│   │
│   ├── presentation/
│   │   ├── providers/
│   │   │   └── dashboard_provider_test_example.dart
│   │   └── screens/
│   │       └── dashboard_screen_test_example.dart
│   │
│   └── integration/
│       └── auth_flow_integration_test_example.dart
│
└── .github/
    └── workflows/
        └── test.yml                       (CI/CD pipeline)
```

---

## Success Metrics

### Short Term (Week 1-2)
- [ ] All example tests run successfully
- [ ] First provider test written and passing
- [ ] CI/CD pipeline running

### Medium Term (Week 3-4)
- [ ] 50%+ code coverage
- [ ] All providers tested
- [ ] Main screens have tests

### Long Term (Month 2+)
- [ ] 70%+ code coverage
- [ ] All screens tested
- [ ] Integration tests for critical flows
- [ ] Zero flaky tests

---

## Version Information

- **Flutter:** 3.38.3
- **Dart:** 3.10.1
- **Riverpod:** 3.x
- **Mocktail:** 1.0.3
- **GoRouter:** 17.x
- **Freezed:** 3.x
- **Research Date:** December 5, 2025

---

**Last Updated:** December 5, 2025

For the most current information, consult:
- Official Flutter documentation at https://docs.flutter.dev/testing
- Riverpod testing guide at https://riverpod.dev/docs/essentials/testing
