본문 바로가기
Frontend, Client/Flutter

[Flutter] 플러터 - 위젯(widget) 테스트

by ggyongi 2022. 12. 9.

위젯 테스트 : https://flutter-ko.dev/docs/cookbook/testing/widget/introduction

 

a. flutter_test 의존성 추가

근데 기본적으로 의존성이 걸려있어서 따로 추가할 필요가 없다.

dev_dependencies:
  flutter_test:
    sdk: flutter

 

b. 테스트할 위젯 생성

class MyWidget extends StatelessWidget {
  final String title;
  final String message;

  const MyWidget({
    Key key,
    @required this.title,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        appBar: AppBar(
          title: Text(title),
        ),
        body: Center(
          child: Text(message),
        ),
      ),
    );
  }
}

 

c. testWidgets 생성

크게 다음 과정을 따라가며 테스트를 진행한다.

  1. WidgetTest가 제공하는 pumpWidget() 메서드로 주어진 위젯을 빌드하고 렌더링한다.
  2. Finder를 통해 나의 위젯을 찾는다.
  3. Matcher로 위젯을 verify한다.

테스트 예시)

void main() {
  testWidgets('MyWidget has a title and message', (WidgetTester tester) async {
    // Create the widget by telling the tester to build it.
    await tester.pumpWidget(MyWidget(title: 'T', message: 'M'));

    // Create the Finders.
    final titleFinder = find.text('T');
    final messageFinder = find.text('M');

		// Use the `findsOneWidget` matcher provided by flutter_test to verify
    // that the Text widgets appear exactly once in the widget tree.
    expect(titleFinder, findsOneWidget);
    expect(messageFinder, findsOneWidget);
  });
}

 

 

기타 도움이 될 자료들

findsOneWidget : 위젯이 1개 존재함
findsNothing : 위젯이 존재하지 않음
findsWidgets : 1개 또는 2개 이상의 위젯이 존재함
findsNWidgets : 특정 N개의 위젯이 존재함

 

📘 비전공자 개발자 취업 성공기 시리즈

개발자가 되고 싶었던 한 비전공자의 1년 4개월 이야기
막막했던 시작부터 좌절, 그리고 합격까지의 여정을 기록했습니다

 

비전공자 네카라 신입 취업 노하우

시행착오 끝에 얻어낸 취업 노하우가 모두 담긴 전자책!

kmong.com

댓글