[Flutter] Unit Test

jaehee kim·2021년 9월 23일
1

Flutter

목록 보기
15/20
post-thumbnail

Unit Test?

Unit Test는 method, class 단위 의 test를 진행한다. Unit Test의 목적은 다양한 조건에서 unit의 로직을 검증하는 것이다.



Example

1.Add the test dependency

test package를 추가한다.

2. Create a test file

test폴더 안에 test파일을 생성한다.
이때, 파일이름은 [테스트 이름]_test.dart 로 작성한다.

test/
    counter_test.dart

3. Create a class to test

test할 class를 생성한다.

class Counter {
  int value = 0;

  void increment() => value++;
  void decrement() => value--;
}

4. Write a test for our class

2번에서 생성한 [테스트 이름]_test.dart 파일에 테스트 코드를 작성한다.
여기서 expect 함수를 이용해서 결과가 맞는지 체크할 수 있다.

import 'package:test/test.dart';
import 'package:counter_app/counter.dart';

void main() {
  test('Counter value should be incremented', () {
    final counter = Counter();
    counter.increment();
    
    expect(counter.value, 1);
  });
}

5. Combine multiple tests in a group

group 함수를 이용해서 서로 관련있는 것들을 묶어서 test할 수 있다.

import 'package:test/test.dart';
import 'package:counter_app/counter.dart';

void main() {
  group('Counter', () {
    test('value should start at 0', () {
      expect(Counter().value, 0);
    });

    test('value should be incremented', () {
      final counter = Counter();
      counter.increment();

      expect(counter.value, 1);
    });

    test('value should be decremented', () {
      final counter = Counter();
      counter.decrement();

      expect(counter.value, -1);
    });
  });
}

6. Run the tests

terminal에서 test를 실행한다.

flutter test test/[테스트 파일]

테스트 결과





Reference

Flutter - An introduction to unit testing

0개의 댓글