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 3,691 times
1 Answers
11
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
- 623,577
- 216
- 2,003
- 1,567
-
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
-
@GünterZöchbauer do you think is better to use a factory constructor instead of a named constructor? And, better to use this factory constructor instead of the getter used on the example? – selan Jul 29 '22 at 09:55
-
@selan yes, you could use a factory constructor, but then you would be hiding that it is a singleton, which might be surprising to the caller. I prefer to make non-standard things more obvious. If you prefer the opaque style, then go ahead. I'm not aware of any other advantages/disadvantages than the mentioned preference. – Günter Zöchbauer Aug 02 '22 at 13:12