Stone Monarch
Stone Monarch

Reputation: 395

Dart test cannot access local variables

Im trying to write some dart unit tests and can not figure out how to get setUp() to run. Tried it with both flutter_test.dart and test.dart. Adding a Breakpoint and debugging the test shows that setUp() is not being run.

Versions:

Flutter 2.3.0-2.0.pre.79 • channel master • https://github.com/flutter/flutter.git
Framework • revision b3f7ebe069 (4 days ago) • 2021-05-08 08:54:02 +0800
Engine • revision f57e986aa8
Tools • Dart 2.14.0 (build 2.14.0-74.0.dev)

dev_dependencies:
  flutter_test:
    sdk: flutter
  test: ^1.16.8

Following the readme for test package and also Shailen Tuli's blog I have came up with this test

// import 'package:flutter_test/flutter_test.dart';
import 'package:test/test.dart';

void main() {
  int int1;
  int int2;

  setUp(() {
    int1 = 1;
    int2 = 2;
  });

  test(
    'Check int1 and int2',
    () {
      print(int1);
      print(int2);
    },
  );
}

Error output is The non-nullable local variable 'int1' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.

Not sure why it is not running. Tried adding this. in front and it threw more errors.

Upvotes: 2

Views: 1229

Answers (1)

Stone Monarch
Stone Monarch

Reputation: 395

import 'package:test/test.dart';

void main() {
  late int int1;
  late int int2;

  setUp(() {
    int1 = 1;
    int2 = 2;
  });

  test(
    'Check int1 and int2',
    () {
      print(int1);
      print(int2);
    },
  );
}

Null safety. RIP. Add late keyword to initialize a variable when it is first read, rather than when it's created.

Upvotes: 11

Related Questions