<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Tarun Sharma</title>
    <description>The latest articles on DEV Community by Tarun Sharma (@mrtarunsaraswat).</description>
    <link>https://dev.to/mrtarunsaraswat</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F330120%2Faff4301a-f3d4-4df3-8c59-3ca021da6276.jpeg</url>
      <title>DEV Community: Tarun Sharma</title>
      <link>https://dev.to/mrtarunsaraswat</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mrtarunsaraswat"/>
    <language>en</language>
    <item>
      <title>Flutter Testing : Authentication Flow</title>
      <dc:creator>Tarun Sharma</dc:creator>
      <pubDate>Sun, 03 Sep 2023 09:31:55 +0000</pubDate>
      <link>https://dev.to/mrtarunsaraswat/flutter-testing-authentication-flow-5di</link>
      <guid>https://dev.to/mrtarunsaraswat/flutter-testing-authentication-flow-5di</guid>
      <description>&lt;p&gt;This document provides a comprehensive example of testing an authentication flow using the AuthForm widget. We'll cover unit testing for validation logic, widget testing for UI interactions, and integration testing for the entire authentication process.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/lib/main.dart"&gt;Auth-Form Widget&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The AuthForm widget is a form for user authentication. It includes input fields for email and password, along with validation logic and a submit button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AuthForm extends StatefulWidget {
  const AuthForm({super.key});

  @override
  State&amp;lt;AuthForm&amp;gt; createState() =&amp;gt; _AuthFormState();
}

class _AuthFormState extends State&amp;lt;AuthForm&amp;gt; {
  @override
  Widget build(BuildContext context) {
    AuthLogic authLogic = AuthLogic();
    return Scaffold(
      appBar: AppBar(
        title: const Text("Testing example"),
      ),
      body: Form(
        key: authLogic.formKey,
        child: Column(
          children: [
            TextFormField(
              key: const Key('emailField'),
              controller: authLogic.emailController,
              validator: authLogic.emailValidator,
              decoration: const InputDecoration(labelText: 'Email'),
            ),
            TextFormField(
              key: const Key('passwordField'),
              controller: authLogic.passwordController,
              validator: authLogic.passwordValidator,
              decoration: const InputDecoration(labelText: 'Password'),
            ),
            ElevatedButton(
              key: const Key('submitButton'),
              onPressed: authLogic.submitForm,
              child: const Text('Submit'),
            ),
          ],
        ),
      ),
    );
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/lib/logic.dart"&gt;Auth-Form Logic&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';

class AuthLogic {
  final formKey = GlobalKey&amp;lt;FormState&amp;gt;();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();

  String? emailValidator(String? value) {
    if (value == null || value.isEmpty || !value.contains('@')) {
      return 'Invalid email';
    }
    return null;
  }

  String? passwordValidator(String? value) {
    if (value == null || value.isEmpty || value.length &amp;lt; 6) {
      return 'Password must be at least 6 characters';
    }
    return null;
  }

  void submitForm() {
    if (formKey.currentState!.validate()) {
      final email = emailController.text;
      final password = passwordController.text;

      // Perform authentication logic
      if (email == 'test@example.com' &amp;amp;&amp;amp; password == 'password123') {
        // If credentials are valid, you can trigger a success action here
        // For now, let's print a success message
        print('Authentication successful');
      } else {
        // If credentials are invalid, you can trigger a failure action here
        // For now, let's print an error message
        print('Authentication failed');
      }
    }
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;main.dart&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:auth_example/logic.dart';
import 'package:flutter/material.dart';
import 'package:flutter_driver/driver_extension.dart';

void main() {
  enableFlutterDriverExtension();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Testing Example'
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const AuthForm(),
    );
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/pubspec.yaml"&gt;Dev dependencies&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
dev_dependencies:
  flutter_driver:
    sdk: flutter
  flutter_test:
    sdk: flutter
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/test/auth_form_unit_test.dart"&gt;Unit Test&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unit tests focus on testing individual components of the AuthForm widget, specifically the validation logic for email and password fields.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter_test/flutter_test.dart';
import 'package:auth_example/auth_form.dart';

void main() {
  group('AuthForm Unit Tests', () {
    // Test for a valid email address
    test('Valid email', () {
      // Arrange: Create a validator function for email validation
      final validator = AuthForm()._emailValidator;

      // Act: Invoke the validator with a valid email
      final result = validator('test@example.com');

      // Assert: Ensure the result is null, indicating a valid email
      expect(result, null);
    });

    // Test for an invalid email address
    test('Invalid email', () {
      // Arrange: Create a validator function for email validation
      final validator = AuthForm()._emailValidator;

      // Act: Invoke the validator with an invalid email
      final result = validator('invalid_email');

      // Assert: Ensure the result is 'Invalid email', indicating an error
      expect(result, 'Invalid email');
    });

    // Test for a valid password
    test('Valid password', () {
      // Arrange: Create a validator function for password validation
      final validator = AuthForm()._passwordValidator;

      // Act: Invoke the validator with a valid password
      final result = validator('password123');

      // Assert: Ensure the result is null, indicating a valid password
      expect(result, null);
    });

    // Test for an invalid password
    test('Invalid password', () {
      // Arrange: Create a validator function for password validation
      final validator = AuthForm()._passwordValidator;

      // Act: Invoke the validator with an invalid password
      final result = validator('123');

      // Assert: Ensure the result is 'Password must be at least 6 characters', indicating an error
      expect(result, 'Password must be at least 6 characters');
    });
  });
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/test/widget_test.dart"&gt;Widget Testing&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Widget tests verify the behavior of the AuthForm widget's UI interactions, such as entering data and submitting the form.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:auth_example/auth_form.dart';

void main() {
  testWidgets('AuthForm UI Test', (WidgetTester tester) async {
    // Arrange: Build the widget under test, which is the AuthForm, within a MaterialApp.
    await tester.pumpWidget(MaterialApp(home: AuthForm()));

    // Find the email, password, and submit button widgets using their Key identifiers.
    final emailField = find.byKey(Key('emailField'));
    final passwordField = find.byKey(Key('passwordField'));
    final submitButton = find.byKey(Key('submitButton'));

    // Act: Enter text into the email and password fields.
    await tester.enterText(emailField, 'test@example.com');
    await tester.enterText(passwordField, 'password123');

    // Tap the submit button to trigger the form submission.
    await tester.tap(submitButton);
    await tester.pump(); // Complete the frame transition.

    // Assert: Check that the text 'Form submitted' is found in the widget tree.
    expect(find.text('Form submitted'), findsOneWidget);
  });
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/mrtarunsaraswat/flutter-testing/blob/main/test/auth_form_integration_test.dart"&gt;Integration Test &lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Integration tests simulate the entire authentication flow, combining multiple components and interactions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import 'package:flutter_driver/flutter_driver.dart';
import 'package:flutter_test/flutter_test.dart' as test;

void main() {
  test.group('AuthForm Integration Test', () {
    FlutterDriver? driver;

    // Connect to the app before running tests
    test.setUpAll(() async {
      // Establish a connection to the Flutter app running on a device or emulator.
      driver = await FlutterDriver.connect(
        // dartVmServiceUrl is a URL used for connecting to the Dart VM service,
        // which is a debugging and profiling service provided by the Dart runtime.
        dartVmServiceUrl: "ws://127.0.0.1:58557/lTla2qH-HXs=/ws",
        printCommunication: true, // Print communication logs for debugging.
      );
    });

    // Close the connection after tests are done
    test.tearDownAll(() async {
      if (driver != null) {
        // Close the FlutterDriver connection.
        driver?.close();
      }
    });

    // Test for successful authentication
    test.test('Successful authentication', () async {
      // Find email, password, and submit button widgets using their value keys.
      final emailField = find.byValueKey('emailField');
      final passwordField = find.byValueKey('passwordField');
      final submitButton = find.byValueKey('submitButton');

      // Tap the email field and enter a valid email.
      await driver?.tap(emailField);
      await driver?.enterText('test@example.com');

      // Tap the password field and enter a valid password.
      await driver?.tap(passwordField);
      await driver?.enterText('password123');

      // Tap the submit button to simulate a form submission.
      await driver?.tap(submitButton);
    }, timeout: test.Timeout.none); // No timeout for this test.

    // Test for failed authentication
    test.test('Failed authentication', () async {
      // Find email, password, and submit button widgets using their value keys.
      final emailField = find.byValueKey('emailField');
      final passwordField = find.byValueKey('passwordField');
      final submitButton = find.byValueKey('submitButton');

      // Tap the email field and enter a valid email.
      await driver?.tap(emailField);
      await driver?.enterText('test@example.com');

      // Tap the password field and enter an invalid password.
      await driver?.tap(passwordField);
      await driver?.enterText('123'); // Invalid password

      // Tap the submit button to simulate a form submission.
      await driver?.tap(submitButton);
    }, timeout: test.Timeout.none); // No timeout for this test.
  });
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This detailed documentation provides a structured overview of each testing aspect for the "auth_example" app, including the AuthForm widget, unit tests, widget tests, and integration tests. You can use this documentation as a reference to understand and implement testing strategies in your Flutter app.&lt;/p&gt;

</description>
      <category>flutter</category>
      <category>testing</category>
      <category>fluttertesting</category>
      <category>dart</category>
    </item>
  </channel>
</rss>
