Check return value / thrown error or exception and calls to print during unit tests in Dart
22:58 04 Nov 2025

The following code is a simplification of the code that I have and may not disclose:

class Logger {
    var _loggingStarted = false;

    void startLogging() {
        if (!_loggingStarted) {
            _loggingStarted = true;
            print('Logging started');
        } else {
            throw StateError('Logging has already been started');
        }
    }

    bool get loggingStarted => _loggingStarted;

    void log(String message) {
        if (_loggingStarted) {
            print(message);
        } else {
            throw StateError('Logging has not been started yet');
        }
    }

    void stopLogging() {
        if (_loggingStarted) {
            _loggingStarted = false;
            print('Logging stopped');
        } else {
            throw StateError('Logging has not been started yet');
        }
    }
}

void main() {
    test('Testing class Logger', () async {
        final instance = Logger();
        await expectLater(() => instance.log('Message'), allOf(prints(''), throwsStateError)); // This gives me currently a NoSuchMethodError
    });
}

How can I check that the function log throws a StateError and prints nothing to the console in the same expect / expectLater statement?

Or is there no way around writing a relatively long callback like the following?

await expectLater(() {
    try {
        instance.log('Message');
        fail('The call to function log must throw a StateError, but did not throw anything');
    } on StateError {
        return;
    } on Object catch (error) {
        fail('The call to function log must throw a StateError, but threw a(n) ${error.runtimeType.toString()}'); 
    }
}, prints(''));

The NoSuchMethodError that I currently get is printed like the following to the Test Results window in Visual Studio Code:

NoSuchMethodError: The method 'describeMismatch' was called on null.

Receiver: null

Tried calling: describeMismatch(Closure: () => void, Instance of 'StringDescription', null, false)

package:matcher expectLater

package:flutter_test/src/widget_tester.dart 508:8 expectLater

.dart :13 main.

flutter dart unit-testing