Flutter ve React Native'de Birim Testleri Yazma
Birim testler, kodunuzun küçük parçalarının beklendiği gibi çalışıp çalışmadığını kontrol eder. Flutter ve React Native'de bu testler projenizi güvenilir tutmanın temelini oluşturur.
Flutter projelerinde testler `test` paketi ile yazılır. Önce `pubspec.yaml` dosyasına bağımlılık ekleyin:
1dev_dependencies:2test: ^1.24.0Sonra test dosyası oluşturun. Örneğin, bir hesap makinesi fonksiyonunu test edelim:
1// calculator.dart2int topla(int a, int b) {3return a + b;4}Test dosyasını `test/calculator_test.dart` konumunda yazın:
1import 'package:test/test.dart';2import 'package:your_app/calculator.dart';34void main() {5group('Hesap Makinesi Testleri', () {6test('2 + 3 = 5 olmalı', () {7expect(topla(2, 3), equals(5));8});910test('Negatif sayılarla çalışmalı', () {11expect(topla(-2, 3), equals(1));12});13});14}Testleri çalıştırmak için terminal'de:
1flutter testÇıktı:
1Hesap Makinesi Testleri22 + 3 = 5 olmalı3Negatif sayılarla çalışmalıReact Native'de Jest kullanılır. Kurulum:
1npm install --save-dev jest @testing-library/react-native`package.json` içine test script'i ekleyin:
1"scripts": {2"test": "jest"3}Aynı hesap makinesi fonksiyonunu test edin:
1// calculator.js2export const topla = (a, b) => a + b;Test dosyası `__tests__/calculator.test.js`:
1import { topla } from '../calculator';23describe('Hesap Makinesi', () => {4it('2 + 3 = 5 olmalı', () => {5expect(topla(2, 3)).toBe(5);6});78it('Negatif sayılarla çalışmalı', () => {9expect(topla(-2, 3)).toBe(1);10});11});Testleri çalıştırın:
1npm testÇıktı:
1PASS __tests__/calculator.test.js2Hesap Makinesi32 + 3 = 5 olmalı (2 ms)4Negatif sayılarla çalışmalı (1 ms)Flutter'da `expect()` ve `test()` doğrudan paketten gelir. React Native'de Jest'in `it()` ve `expect()` fonksiyonlarını kullanırsınız. Her iki platformda da `group()` (Flutter) veya `describe()` (React Native) ile testleri organize edersiniz.
Testleri düzenli çalıştırmak, hataları erken bulmanızı ve refactoring sırasında güven vermeyi sağlar. Başlangıçta kritik fonksiyonlara odaklanın; zaman içinde kapsam artırın.
0 yorum