Skip to main content

One post tagged with "Integration Test"

View All Tags

Testing Trong Flutter

· 2 min read

Giới Thiệu

Testing là một phần quan trọng trong quá trình phát triển ứng dụng Flutter. Flutter hỗ trợ ba loại testing chính:

  • Unit Testing
  • Widget Testing
  • Integration Testing

Unit Testing

Cài đặt Dependencies

dev_dependencies:
test: ^1.24.0
mockito: ^5.4.0
build_runner: ^2.4.0

Ví dụ Unit Test

// Class cần test
class Calculator {
int add(int a, int b) => a + b;
}

// Test file
import 'package:test/test.dart';

void main() {
group('Calculator', () {
late Calculator calculator;

setUp(() {
calculator = Calculator();
});

test('add should return correct sum', () {
expect(calculator.add(2, 3), equals(5));
});
});
}

Widget Testing

Cài đặt

dev_dependencies:
flutter_test:
sdk: flutter

Ví dụ Widget Test

testWidgets('Counter increments smoke test', (WidgetTester tester) async {
await tester.pumpWidget(MyApp());
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);

await tester.tap(find.byIcon(Icons.add));
await tester.pump();

expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});

Integration Testing

Cài đặt

dev_dependencies:
integration_test:
sdk: flutter

Ví dụ Integration Test

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();

testWidgets('Complete flow test', (WidgetTester tester) async {
await tester.pumpWidget(MyApp());

// Login flow
await tester.enterText(
find.byKey(Key('username')),
'testuser'
);
await tester.enterText(
find.byKey(Key('password')),
'password123'
);
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();

// Verify home screen
expect(find.text('Welcome'), findsOneWidget);
});
}

Mocking trong Flutter

Sử dụng Mockito

// Tạo mock class
@GenerateMocks([HttpClient])
void main() {
late MockHttpClient mockHttpClient;

setUp(() {
mockHttpClient = MockHttpClient();
});

test('fetchData returns data on success', () async {
when(mockHttpClient.get(any))
.thenAnswer((_) async => Response('{"data": "test"}', 200));

final result = await DataService(mockHttpClient).fetchData();
expect(result, equals('test'));
});
}

Best Practices

Unit Testing

  • Test một function/method độc lập
  • Tập trung vào business logic
  • Sử dụng mocking cho external dependencies

Widget Testing

  • Test UI components
  • Verify widget rendering
  • Test user interactions

Integration Testing

  • Test complete user flows
  • Verify app behavior end-to-end
  • Test real device interactions

Continuous Integration

Cấu hình GitHub Actions

name: Flutter CI

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@v2
- run: flutter test

Test Coverage

Generating Coverage Reports

# Run tests with coverage
flutter test --coverage

# Generate HTML report
genhtml coverage/lcov.info -o coverage/html

Tài Liệu Tham Khảo