Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 602
Kasper Avatar asked Jan 18 '26 03:01

Kasper


1 Answers

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.

like image 83
Alexandre Ardhuin Avatar answered Jan 19 '26 17:01

Alexandre Ardhuin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!