Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a void function in Dart?

I am new to unit tests in Dart/Flutter and I would like to write a test for a void function. When functions return something I am writing a test like this:

test('Gets user save', () async {
      final userSave = await mockSource!.getUserSave();
      expect(userSave!.age, equals(20));
});

In such a scenario like above expect can be used since getUserSave function returns a user model.

How about checking if test passes of fails for a void/Future function like below? I can not use expect because it does not return a value.

Future<void> clearUserSave() async {
    DatabaseClient mockDBClient = MockDatabaseClientImpl();
    mockDBClient.clear();
}

I use flutter_test and mockito for testing.

like image 288
shuster Avatar asked May 08 '26 06:05

shuster


2 Answers

testing a function that return void :

  expect(
      () async => await functionThatReturnsVoid(),
      isA<void>(),
    );
like image 62
Abhishek Ghimire Avatar answered May 10 '26 10:05

Abhishek Ghimire


Typically a void function will produce a side effect of some sort. When writing a test for a void function, I would check whatever state is effected by the void function before and after calling the function to be sure that the desired side effect has occurred.

In this specific case, you are calling clear on a DatabaseClient. I don't know the specifics of the DatabaseClient api, but I would construct a test where the client contains some data before calling clear, and then check that the data is no longer there after calling clear.

Something along the lines of this:

Future<void> clearUserSave() async {
    DatabaseClient mockDBClient = MockDatabaseClientImpl();
    mockDBClient.add(SOMEDATA);
    expect(mockDBClient.hasData, true);
    mockDBClient.clear();
    expect(mockDBClient.hasData, false);
}
like image 21
mmcdon20 Avatar answered May 10 '26 12:05

mmcdon20



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!