Reputation: 1104
I'm trying to unit test a class that has static void methods.
I'm using Mockito (verify) to check if a void method call another function as expected, but it doesn't work to static methods.
class SystemUtils {
// ...
static void handleError(bool isDebug, FlutterErrorDetails details) {
if (isDebug) {
FlutterError.dumpErrorToConsole(details);
} else {
Crashlytics.instance.onError(details);
}
}
}
Upvotes: 2
Views: 5578
Reputation: 391
What I think you're looking for (example):
Code to be tested:
class TestExpect {
static void noParameter() {
bool inDebugMode = false;
assert(inDebugMode = false);
}
static void hasParameter(bool toBeIgnored) {
bool inDebugMode = false;
assert(inDebugMode = false);
}
}
Unit Testing Code:
void main() {
test('static void method', () {
expect(TestExpect.noParameter, throwsA(isA<AssertionError>()));
});
test('static void method parameter', () {
expect(() => TestExpect.hasParameter(true), throwsA(isA<AssertionError>()));
});
}
Upvotes: 1
Reputation: 1104
I solved changing the class.
The method isn't static anymore and now I receive the external methods in the constructor as default values.
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:flutter/cupertino.dart';
class SystemUtils {
SystemUtils({
debugErrorHandler,
releaseErrorHandler,
}) : _debugErrorHandler =
debugErrorHandler ?? FlutterError.dumpErrorToConsole,
_releaseErrorHandler =
releaseErrorHandler ?? Crashlytics.instance.onError;
final void Function(FlutterErrorDetails) _debugErrorHandler;
final void Function(FlutterErrorDetails) _releaseErrorHandler;
static bool isInDebugMode() {
bool inDebugMode = false;
assert(inDebugMode = true);
return inDebugMode;
}
void handleError(bool isDebug, FlutterErrorDetails details) {
if (isDebug) {
_debugErrorHandler(details);
} else {
_releaseErrorHandler(details);
}
}
}
Now I can replace the method on constructor when I wanted (in tests for example).
group('handleError', () {
test('should call _debugErrorHandler if isDebug is true', () {
const isDebug = true;
const details = FlutterErrorDetails(exception: 'error exception');
void debugErrorHandler(FlutterErrorDetails localDetails) {
expect(localDetails, details);
}
final SystemUtils systemUtils = SystemUtils(debugErrorHandler: debugErrorHandler);
systemUtils.handleError(isDebug, details);
});
});
But I still want to know if it's possible to test void static methods in Dart.
Upvotes: 0