2

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Kasper
  • 12,594
  • 12
  • 41
  • 63

2 Answers2

4

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.

Alexandre Ardhuin
  • 71,959
  • 15
  • 151
  • 132
2

One option that comes to my mind is to run the code you want to test in a new process Process.run() or Process.start() and check the exit code at the end. You can use stdin/stdout to communicate with the process (send keyboard input, read output)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567