Is it possible to reset the state of dispatch_once code in a unit test tearDown?
I think it would be nice if our unit tests could run from a really clean state, but we are struggling with dispatch_once and some singletons made with dispatch once.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I should note first that this isn’t a good thing to do in any situation other than testing; even then, proceed with care — AliSoftware provides some details and example code in comments below. See also the interesting answers at Can I declare a
dispatch_once_tpredicate as a member variable instead of static?, including some important information from the horse’s mouth.dispatch_once_tis atypedefdlong. Its false value is 0. If you reset that flag to 0,dispatch_once()will run again. Your problem is “just” how to change the value of a static variable from another compilation unit. For this, I think you need a debug/unit test hook, like so:MakeWhoopie.h
MakeWhoopie.m
(You could also move
once_tokenup to file level and change it directly.)Trying this out:
Results in: