0

I am writing a test case for the null-aware operation '!', but not able to catch the exception.

Function:

 int? notNullAssertionForException() {
    String? country;
    return country!.length;
  }

Test:

test('Not Null Assertion For Exception Test', () {
    final nullSafety = NullSafety();
    expect(nullSafety.notNullAssertionForException(), null);
  });

Error: Null check operator used on a null value

I am not able to figure out the way to test this. How I can pass this test?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147
  • Does this answer your question? [How do you unittest exceptions in Dart?](https://stackoverflow.com/questions/13298969/how-do-you-unittest-exceptions-in-dart) – jamesdlin Mar 22 '21 at 22:24
  • @jamesdlin: But in my case, I am not getting any exception to catch, it would be great if you give an answer above, Thanks!! – Jitesh Mohite Mar 23 '21 at 03:19
  • As explained by the linked answer, you must test for a exceptions by passing a *function* to `expect()`. Otherwise it will throw an exception immediately before `expect` is even called. `expect(notNullAssertionForException, throwsA(isA()));` works fine. – jamesdlin Mar 23 '21 at 04:50
  • expect(() => nullSafety.notNullAssertionForException(), throwsA(isA())); this working – Jitesh Mohite Mar 23 '21 at 17:02

0 Answers0