11. Testing

Automatically checking that nothing is broken

Goals of this chapter

1

Repository

Run real SQL on an in-memory DB

2

Domain & packet data

Check pure functions

3

ViewModel & connection

Check with the DB and sensor swapped out

Repository tests

test/repository_test.dart
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:motion_app/infrastructure/database/app_database.dart';
import 'package:motion_app/repository/session/session_repository.dart';
import 'package:motion_app/repository/user/user_repository.dart';

void main() {
  late AppDatabase db;
  late UserRepository users;
  late SessionRepository sessions;

  setUp(() {
    db = AppDatabase(NativeDatabase.memory()); // empty DB for each test
    users = UserRepository(db);
    sessions = SessionRepository(db);
  });
  tearDown(() => db.close());

  Future<void> addSession(String userId, double peakGyro1) => sessions.add(
        userId: userId,
        durationSec: 3,
        sampleCount: 300,
        peakGyro1: peakGyro1,
        peakGyro2: 0,
        peakAcc1: 1,
        peakAcc2: 1,
      );

  test('測定履歴は新しい順に並ぶ', () async {
    final user = await users.create(name: 'たろう');
    await addSession(user.id, 500);
    await Future<void>.delayed(const Duration(milliseconds: 5));
    await addSession(user.id, 600);

    final history = await sessions.getByUser(user.id);
    expect(history.map((s) => s.peakGyro1), [600, 500]);
  });

  test('ユーザーを削除すると測定履歴も消える', () async {
    final user = await users.create(name: 'たろう');
    await addSession(user.id, 500);

    await users.deleteUser(user.id);

    expect(await sessions.getByUser(user.id), isEmpty);
  });
}

Domain tests

test/domain_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:motion_app/domain/motion_analyzer.dart';
import 'package:motion_app/service/imu/imu_device.dart';

ImuSample sample(double gyro1z, {double acc1z = 1}) => ImuSample(
      count: 0,
      acc1: Vec3(0, 0, acc1z),
      gyro1: Vec3(0, 0, gyro1z),
      acc2: const Vec3(0, 0, 1),
      gyro2: const Vec3(3, 4, 0), // magnitude is 5
    );

void main() {
  test('最大値と測定時間を求める', () {
    final summary = MotionAnalyzer.summarize([
      sample(100),
      sample(-700, acc1z: 3), // Compare by magnitude even if the direction is reversed
      sample(300),
    ]);

    expect(summary.peakGyro1, 700);
    expect(summary.peakGyro2, 5);
    expect(summary.peakAcc1, 3);
    expect(summary.sampleCount, 3);
    expect(summary.durationSec, closeTo(0.03, 1e-9)); // 3 samples at 100Hz
  });

  test('自己ベストは過去の記録をすべて上回ったときだけ', () {
    expect(MotionAnalyzer.isPersonalBest(500, []), isTrue); // first time
    expect(MotionAnalyzer.isPersonalBest(500, [400, 450]), isTrue);
    expect(MotionAnalyzer.isPersonalBest(500, [400, 500]), isFalse); // an equal value is not a new best
  });
}
  • Checking boundary values (an equal value isn’t a personal best) catches mistakes in the rules

Packet data tests

test/imu_packet_test.dart
import 'dart:typed_data';

import 'package:flutter_test/flutter_test.dart';
import 'package:motion_app/service/imu/imu_packet.dart';

// Build a 52-byte packet in the same format as the real device
Uint8List packet({int count = 7}) {
  final data = ByteData(52)
    ..setUint8(0, 0x01)
    ..setUint8(1, 0x01)
    ..setUint16(2, count, Endian.little);
  final values = [0.0, 0.0, 1.0, 10.0, 20.0, 30.0, 0.5, 0.5, 0.5, -1.0, -2.0, -3.0];
  for (var i = 0; i < values.length; i++) {
    data.setFloat32(4 + i * 4, values[i], Endian.little);
  }
  return data.buffer.asUint8List();
}

void main() {
  test('52byteのパケットを6軸×2のデータに変換する', () {
    final s = ImuPacket.tryParse(packet())!;
    expect(s.count, 7);
    expect(s.acc1.z, 1.0);
    expect(s.gyro1.y, 20.0);
    expect(s.acc2.x, 0.5);
    expect(s.gyro2.z, -3.0);
  });

  test('長さや識別子が違うデータは無視する', () {
    expect(ImuPacket.tryParse(Uint8List.fromList('device_version,0.3.0'.codeUnits)), isNull);
    final wrongHeader = packet()..[0] = 0x02;
    expect(ImuPacket.tryParse(wrongHeader), isNull);
  });
}
  • By building byte sequences in the same format as the hardware yourself, you can verify parsing without hardware

ViewModel tests

test/view_model_test.dart
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/infrastructure/database/app_database.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/service/imu/fake_imu_device.dart';
import 'package:motion_app/ui/measurement/view_model/measurement_view_model.dart';
import 'package:motion_app/ui/user_list/view_model/user_list_view_model.dart';

void main() {
  late ProviderContainer container;

  setUp(() {
    // Inject an in-memory DB and the fake sensor instead of the real DB and sensor
    container = ProviderContainer(overrides: [
      appDatabaseProvider.overrideWithValue(AppDatabase(NativeDatabase.memory())),
      imuDeviceProvider.overrideWithValue(FakeImuDevice()),
    ]);
  });
  tearDown(() => container.dispose());

  test('名前が空ならユーザーを追加しない', () async {
    // Simulate the screen being shown (it is disposed automatically if nobody subscribes)
    final sub = container.listen(userListViewModelProvider, (_, _) {});
    final ok = await container.read(userListViewModelProvider.notifier).addUser('  ');

    expect(ok, isFalse);
    expect(container.read(userListViewModelProvider).hasInputError, isTrue);
    sub.close();
  });

  test('測定して保存すると、最大角速度が記録され初回は自己ベストになる', () async {
    final user = await container.read(userRepositoryProvider).create(name: 'たろう');

    final provider = measurementViewModelProvider(user.id);
    final sub = container.listen(provider, (_, _) {}); // simulate the screen being shown
    await container.read(provider.notifier).start();
    await Future<void>.delayed(const Duration(milliseconds: 1600)); // wait for one swing
    final result = await container.read(provider.notifier).stopAndSave();
    sub.close();

    expect(result!.isPersonalBest, isTrue);
    final history = await container.read(sessionRepositoryProvider).getByUser(user.id);
    expect(history.single.peakGyro1, greaterThan(700)); // the fake sensor peaks at about 800dps
  });
}

Connection tests

test/imu_connection_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:motion_app/provider/imu_connection.dart';
import 'package:motion_app/provider/providers.dart';
import 'package:motion_app/service/imu/fake_imu_device.dart';

void main() {
  late FakeImuDevice device;
  late ProviderContainer container;

  // Let pending work (connecting, reading the battery) proceed
  Future<void> settle() => Future<void>.delayed(Duration.zero);

  setUp(() {
    device = FakeImuDevice();
    container = ProviderContainer(overrides: [
      imuDeviceProvider.overrideWithValue(device),
    ]);
    // Like App: connects automatically once subscribed
    container.listen(imuConnectionProvider, (_, _) {});
  });
  tearDown(() => container.dispose());

  test('起動すると自動で接続し、電池残量を読む', () async {
    await settle();

    final state = container.read(imuConnectionProvider);
    expect(state.status, ImuConnectionStatus.connected);
    expect(state.batteryLevel, 99); // the fake battery drops 1% on every read
  });

  test('接続中に切れたら、自動でつなぎ直す', () async {
    await settle();
    await device.disconnect(); // simulate the power going off
    await settle();

    final state = container.read(imuConnectionProvider);
    expect(state.status, ImuConnectionStatus.connected);
    expect(state.batteryLevel, 98); // read again after reconnecting
  });

  test('自分で切断したときは、つなぎ直さない', () async {
    await settle();
    await container.read(imuConnectionProvider.notifier).disconnect();
    await settle();

    expect(container.read(imuConnectionProvider).status,
        ImuConnectionStatus.disconnected);
  });
}
  • Call the fake’s disconnect() directly to simulate “the power went off”
  • Battery at 98% = proof that it was read again after reconnecting

Key points

  • ProviderContainer(overrides: [...]) injects substitutes for the real things
    • DB → in-memory DB / sensor → fake sensor
  • container.listen(...) simulates “the screen is being shown”
    • Because a ViewModel nobody uses is disposed automatically
flutter test

Checkpoint

CHECK 0 / 4