I have created a class as singleton making a static method to get the instance of that class but while unit test I am not able to mock that class. Is there any other way in dart to only create a single instance and that can be easily unit tested.
Asked
Active
Viewed 2,617 times
1 Answers
6
There are different ways depending on what your exact requirements are.
You could use an additional class to access the singleton where you can create multiple instances while still being guaranteed that the value it allows to access will be a singleton:
class MySingleton {
static final MySingleton value = MySingleton.();
MySingleton._();
}
class MySingletonHelper {
MySingleton get value => MySingleton.value;
}
or and alternative way using @visibleForTesting with the limitation that the singleton value can not be final and write access is only limited by the DartAnalyzer, but not by the compiler (I wouldn't consider this a serious limitation):
import 'package:meta/meta.dart';
class MySingleton {
static MySingleton _value = MySingleton.();
static MySingleton value => get _value;
@visibleForTesting
static set value(MySingleton val) => _value = val;
MySingleton._();
}
Günter Zöchbauer
- 558,509
- 191
- 1,911
- 1,506
-
can you show me a way using factory constructor,is it possible – Gagan Garcha Mar 08 '19 at 06:16
-
using the factory keyword in dart and making a constructor return instance of it – Gagan Garcha Mar 08 '19 at 06:27
-
The question in https://stackoverflow.com/questions/25756593/dart-factory-constructor-how-is-it-different-to-const-constructor shows a factory constructor (similar to https://www.dartlang.org/guides/language/language-tour#factory-constructors) also https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart/12649574#12649574 – Günter Zöchbauer Mar 08 '19 at 06:29