Mocking static methods, constructors, or top-level functions
masterMockito cannot mock static methods, constructors, or top-level functions because it relies on overriding class instance methods via noSuchMethod.
To make your code testable, consider these refactoring patterns:
- Dependency Injection: Instead of constructing an object inside a function, pass the object as an argument.
// BEFORE: Un-mockable constructor call
void f() {
var foo = Foo();
// ...
}
// AFTER: Inject the dependency
void f(Foo foo) {
// ...
}In your test, you can then pass a MockFoo instance to f.
- Wrapper Systems: Use a wrapper or a service to abstract away static/global calls. For example, instead of using
Directory.currentorFile(), use thefilepackage'sFileSystemabstraction, which allows you to swap aLocalFileSystemfor aMemoryFileSystemduring tests.
// BEFORE:
void f() {
var foo = Foo();
// ...
}
// AFTER
void f(Foo foo) {
// ...
}