Dart – How do you write a test against a function that calls exit()?

Issue

I want to test a function that calls exit.

Basicly, I have a console application, that asks the user if he is sure that he wants a directory to be overwritten. When the users answers “No”, the directory won’t be overwritten, and the program should exit.

promptToDeleteRepo() {
  bool okToDelete = ...
  if(okToDelete) {
    deleteRepo();
  } else {
    exit(0);
  }
}

So I want to test that if the user answers “No”, that the program really exits. But if I test this, my test runner exits.

In python I seem to be able to do something like:

with pytest.raises(SystemExit):
    promptToDeleteRepo();

Is there something like this in Dart?

Solution

You can inject a custom exit function during the tests.

import 'dart:io' as io;

typedef ExitFn(int code);

ExitFn exit = io.exit;

promptToDeleteRepo() {
  bool okToDelete = ...
  if(okToDelete) {
    deleteRepo();
  } else {
    exit(0);
  }
}

and in your test :

int exitCodeUsed;
mylib.exit = (int code) {exitCodeUsed = code};
mylib.promptToDeleteRepo();

A better solution whould have to use zones but there doesn’t seem to be possible to handle exit. It could be worth to file an issue.

Answered By – Alexandre Ardhuin

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *