android - How to shadow singleton with Robolectic? -
i have such singleton:
public class singletona{ private singletona instance = null; private singletona(){ } public static singletona getinstance(){ return instance ; } public static void init(){ system.loadlibrary("alib"); instance = new singletona(); } ...... other methods } as can see, before use , have call singletona.init().but robolectric can not load .so file. want write shadowsingletona replace it, don't know how do.because variable instance private. can 1 help? besides, class singletona third part library can not modification it.
another common way deal dependencies abstract them make them interchangeable , testable.
so assume have great library next api:
class libraryname { public static somesinglethon getinstance(); } first, create abstraction:
public class librarygenericpurpose { public void dosomething(@nonnull string nameofthing) { libraryname.getinstance().dosomething(new event(nameofthing)); } } first note method not static, have add dependency in places calling static methods library. handy have interface such thing.
and change place use from:
class someclass { public void somemethod() { libraryname.getinstance().dosomething(new event(nameofthing)); } } to:
class someclass { @nonnull private librarygenericpurpose library; public someclass(@nonnull librarygenericpurpose library) { this.library = library; } public void somemethod() { library.dosomething("great!"); } } and if don't have control on class life cycle activity or fragment have learn new ways how inject dependencies there.
finally, in tests, don't need use robolectric someclass @ all. , quite these classes librarygenericpurpose not testable on jvm (even robolectric) , quite hard or impossible test in instrumental tests.
Comments
Post a Comment