Flutter/Dart simple unit testing example

Quick guide on how to test a function that doesn't render a widget in Dart/Flutter

Mon, 26 Jun 2023

This is a simple unit test example. We want to test a function that doesn’t render a widget. Here’s an example

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:housemates/utils/theme.dart';

void main() {
  group("App Theme", () {
    test('Should return light theme', () {
      ThemeData lightTheme = themeLight;
      expect(lightTheme.brightness, Brightness.light);
    });
    test('Should return dark theme', () {
      ThemeData darkTheme = themeDark;
      expect(darkTheme.brightness, Brightness.dark);
    });
  });
}

This example groups up all the tests under App Theme and then I run 2 individual tests. This unit tests is just to always verify that I’m loading the correct theme since I do change up my theme often. This is the current app theme

ThemeData themeLight = FlexThemeData.light(
  colors: const FlexSchemeColor(
    primary: Color(0xffe34317),
    primaryContainer: Color(0xfffc744f),
    secondary: Color(0xffd6a32e),
    secondaryContainer: Color(0xfff9c864),
    tertiary: Color(0xff5be3ce),
    tertiaryContainer: Color(0xff85eadb),
    appBarColor: Color(0xfff9c864),
    error: Color(0xffb00020),
  ),
  surfaceMode: FlexSurfaceMode.highScaffoldLowSurfacesVariantDialog,
  blendLevel: 15,
  subThemesData: const FlexSubThemesData(
    blendOnLevel: 10,
    blendOnColors: false,
    useTextTheme: false,
    useM2StyleDividerInM3: true,
    inputDecoratorRadius: 20.0,
  ),
  useMaterial3ErrorColors: true,
  visualDensity: FlexColorScheme.comfortablePlatformDensity,
  useMaterial3: true,
  swapLegacyOnMaterial3: true,
  fontFamily: GoogleFonts.notoSans().fontFamily,
);

ThemeData themeDark = FlexThemeData.dark(
  colors: const FlexSchemeColor(
    primary: Color(0xffe34317),
    primaryContainer: Color(0xfffc744f),
    secondary: Color(0xffd6a32e),
    secondaryContainer: Color(0xfff9c864),
    tertiary: Color(0xff5be3ce),
    tertiaryContainer: Color(0xff85eadb),
    appBarColor: Color(0xfff9c864),
    error: Color(0xffb00020),
  ).defaultError.toDark(10, false),
  surfaceMode: FlexSurfaceMode.highScaffoldLowSurfacesVariantDialog,
  blendLevel: 15,
  subThemesData: const FlexSubThemesData(
    blendOnLevel: 20,
    useTextTheme: false,
    useM2StyleDividerInM3: true,
    inputDecoratorRadius: 20.0,
  ),
  useMaterial3ErrorColors: true,
  visualDensity: FlexColorScheme.comfortablePlatformDensity,
  useMaterial3: true,
  swapLegacyOnMaterial3: true,
  fontFamily: GoogleFonts.notoSans().fontFamily,
);
Buy Me A CoffeeDigitalOcean Referral Badge
Loading...
Edward Beazer

Edward Beazer - I just like to build shit. Sometimes I get stuck for hours, even days while trying to figure out how to solve an issue or implement a new feature. Hope my tips and tutorials can save you some time.

DigitalOcean Referral Badge