How to add user input in dart test?

202 views Asked by At

I'm new to dart and trying out testing. My first programm is a command line tool that takes user input. How can I simulate that during testing?

My function lets the user choose an item out of a list. I'd like to write tests if the function successfully rejects integers too small or too big entered via "readLineSync".

How to create the input in a test? (using test.dart)

1

There are 1 answers

2
APEALED On

If you are using stdin to collect input you can use IOOverrides to override the behavior of stdin. The example I'm using requires you to install mocktail as a dev dependency. Given the funtion:

String? collect() => stdin.readLineSync();

I want to provide my own input during testing:

import 'dart:io' hide stdin;

import 'package:example/example.dart' show collect;
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';

class FakeStdin extends Mock implements Stdin {}

void main() {
  test('collect returns input', () {
    final stdin = FakeStdin();

    when(() => stdin.readLineSync()).thenReturn('input!');

    IOOverrides.runZoned(
      () {
        expect(collect(), equals('input!')); // passes!
      },
      stdin: () => stdin,
    );
  });
}