14

I found out how you can test an exception or error: https://stackoverflow.com/a/54241438/6509751

But how do I test that the following assert works correctly?

void cannotBeNull(dynamic param) {
  assert(param != null);
}

I tried the following, but it does not work. The assertion is simply printed out and the test fails:

void main() {
  test('cannoBeNull assertion', () {
    expect(cannotBeNull(null), throwsA(const TypeMatcher<AssertionError>()));
  });
}
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402

2 Answers2

27

There are two key aspects to this:

  • Pass a callback to expect. When you do that, you can never do something wrong, even if you just instantiate an object. This was already shown in the linked answer.

  • Use throwAssertionError.

  • If you are using pure Dart and not Flutter you can use throwsA(isA<AssertionError>())

Example:

expect(() {
  assert(false);
}, throwsAssertionError);

or

expect(() {
  assert(false);
}, throwsA(isA<AssertionError>()));

Applied to the code from the question:

void main() {
  test('cannoBeNull assertion', () {
    expect(() => cannotBeNull(null), throwsAssertionError);
  });
}

or

void main() {
  test('cannoBeNull assertion', () {
    expect(() => cannotBeNull(null), throwsA(isA<AssertionError>()));
  });
}

Why do we need to pass a callback? Well, if you have a function without parameters, you can also pass a reference to that as well.

If there was no callback, the assertion would be evaluated before expect is executed and there would be no way for expect to catch the error. By passing a callback, we allow expect to call that callback, which allows it to catch the AssertionError and it is able to handle it.

Mark O'Sullivan
  • 10,138
  • 6
  • 39
  • 60
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
0

Applied to the code from the question(This is exactly what worked for me, used throwsA(TypeMatcher() instead of the throwsAssertionError):

void main() {
  test('cannoBeNull assertion', () {
    expect(() => cannotBeNull(null), throwsA(TypeMatcher<AssertionError>()));
  });
}
Rodrick Vy
  • 36
  • 5