หลักการทดสอบวิดเจ็ต
เรียนรู้การเขียนการทดสอบวิดเจ็ตเพื่อตรวจสอบส่วนติดต่อผู้ใช้และพฤติกรรมของวิดเจ็ตแต่ละรายการแยกจากกัน พร้อมรับประกันความถูกต้องของการแสดงผล
หลักการทดสอบวิดเจ็ต เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Widget Testing?
Welcome to widget testing! It's a key part of building robust Flutter apps.
Widget tests let you check if your individual UI components (widgets) look and behave as expected. Think of it as putting each piece of your app under a microscope.
- Focus: Individual widgets.
- Goal: Verify UI rendering and interaction in isolation.
Diving into `flutter_test`
Flutter provides a special package called flutter_test for writing widget tests. It's automatically included in new Flutter projects.
The core of widget testing is the testWidgets function. It gives you a WidgetTester to interact with your widgets and an environment to run them.
Where Do Tests Go?
Flutter test files typically live in the test/ folder of your project. For example, if you have a widget in lib/my_widget.dart, its test might be in test/my_widget_test.dart.
Each test file starts with importing package:flutter_test/flutter_test.dart and defines one or more testWidgets blocks.
Your Testing Helper: `WidgetTester`
The WidgetTester is your main tool for interacting with widgets during a test. It provides methods to:
pumpWidget(): Renders a widget tree.find: Locates widgets in the tree.tap(): Simulates a tap on a widget.pump(): Rebuilds the widget tree, often after an interaction.
It helps simulate how a user would interact with your app.
Testing a Basic Stateless Widget
Let's test a simple StatelessWidget. Imagine a widget that just shows some text.
We'll use tester.pumpWidget() to display our widget, then tester.find to locate the text, and finally expect() to assert that it's there.
import 'package:flutter/material.dart';
class MyTextWidget extends StatelessWidget {
final String message;
const MyTextWidget({Key? key, required this.message}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Test')),
body: Center(
child: Text(message),
),
),
);
}
}
void main() {
runApp(const MyTextWidget(message: "Hello CoddyKit!"));
}Code: Testing `MyTextWidget`
Here's how you'd write a test for our MyTextWidget. Notice how we wrap it in MaterialApp and Scaffold to give it a proper context for rendering.
We use find.text() to locate the text and expect() with findsOneWidget to confirm its presence.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// Assume MyTextWidget is defined in a separate file or above for testing
class MyTextWidget extends StatelessWidget {
final String message;
const MyTextWidget({Key? key, required this.message}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Test')),
body: Center(
child: Text(message),
),
),
);
}
}
void main() {
testWidgets('MyTextWidget displays correct message', (WidgetTester tester) async {
// Build our widget and trigger a frame.
await tester.pumpWidget(const MyTextWidget(message: 'Hello CoddyKit!'));
// Verify that our message appears.
expect(find.text('Hello CoddyKit!'), findsOneWidget);
expect(find.text('Goodbye!'), findsNothing);
});
}Interacting with Widgets
Widget tests can simulate user interactions. This is crucial for testing StatefulWidgets or widgets with buttons, text fields, etc.
tester.tap(finder): Simulates a tap on the widget found byfinder.tester.enterText(finder, text): Enters text into aTextField.tester.pump(): After an interaction that causes state changes (like a button tap), you must callpump()to rebuild the UI and reflect those changes.
Testing a Basic Stateful Widget
Let's create a simple counter widget. It has a text displaying a number and a button to increment it. We'll test its initial state and then its behavior after a tap.
import 'package:flutter/material.dart';
class CounterWidget extends StatefulWidget {
const CounterWidget({Key? key}) : super(key: key);
@override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
key: const Key('counterText'), // Added key for easy finding
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
key: const Key('incrementButton'), // Added key
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
}
void main() {
runApp(const CounterWidget());
}Code: Testing `CounterWidget`
Here's the test for our CounterWidget. We first verify the initial count, then simulate a tap on the increment button using its Key, and finally assert that the count has updated.
Remember to call tester.pump() after tester.tap() to rebuild the UI and see the state change.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// Assume CounterWidget is defined in a separate file or above for testing
class CounterWidget extends StatefulWidget {
const CounterWidget({Key? key}) : super(key: key);
@override
State<CounterWidget> createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() { _counter++; });
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text('You have pushed the button this many times:'),
Text('$_counter', key: const Key('counterText'), style: Theme.of(context).textTheme.headlineMedium),
],
),
),
floatingActionButton: FloatingActionButton(
key: const Key('incrementButton'),
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
),
);
}
}
void main() {
testWidgets('CounterWidget increments counter on button tap', (WidgetTester tester) async {
// Build our CounterWidget.
await tester.pumpWidget(const CounterWidget());
// Verify that the counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the 'increment' icon and trigger a frame.
await tester.tap(find.byKey(const Key('incrementButton')));
await tester.pump(); // Rebuild the widget after interaction
// Verify that the counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}Essential Test Matchers
When writing tests, you'll use expect() with various "matchers" to verify conditions. Here are some common ones:
findsOneWidget: Expects exactly one widget matching the finder.findsNWidgets(N): Expects exactly N widgets.findsNothing: Expects no widgets matching the finder.findsWidgets: Expects one or more widgets.
These help you precisely assert what should or shouldn't be on screen.
Quick Check on Testing
Imagine you have a Text('Hello World') widget. Which find method would you use to confirm this text is visible on the screen after calling tester.pumpWidget()?
Recap: Widget Testing Basics
Great job! You've learned the fundamentals of widget testing:
- Widget tests verify individual UI components.
- The
flutter_testpackage provides tools liketestWidgetsandWidgetTester. - You use
tester.pumpWidget()to render,findto locate, andexpect()with matchers to assert. tester.tap()andtester.pump()simulate user interaction and update the UI.
Next, you'll explore more advanced testing techniques!
คำถามที่พบบ่อย
บทเรียน “หลักการทดสอบวิดเจ็ต” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “หลักการทดสอบวิดเจ็ต” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “หลักการทดสอบวิดเจ็ต”
เรียนรู้การเขียนการทดสอบวิดเจ็ตเพื่อตรวจสอบส่วนติดต่อผู้ใช้และพฤติกรรมของวิดเจ็ตแต่ละรายการแยกจากกัน พร้อมรับประกันความถูกต้องของการแสดงผล คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “หลักการทดสอบวิดเจ็ต” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม
ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ