NotificationCenter
and DependencyValues
#218
Replies: 1 comment
-
Hi @kielgillard, a few things come to mind while reading this:
So, while you do bring up good points in favor of a There is one situation in which it would be beneficial to have a controlled Notification Center, but it requires enough design decisions that it starts to not feel appropriate for this library. The situation I have in mind is where you want to be able to prove that your feature posted a notification. That would require some kind of mock center that buffers each notification posted so that you could then assert on it. And even better if there was some kind of exhaustive testing where it failed the test suite if all notifications were not asserted on. However, there are a lot of design decisions to think through before such a thing could become a reality, and so it may be better for someone to maintain their own version of it, or open source it. |
Beta Was this translation helpful? Give feedback.
-
Hello all,
I would like to understand why smarter people than I seem to think
NotificationCenter.default
is not a dependency that ought to be better controlled since it is so easy for other objects in the runtime/environment to post notifications during tests.I recently opened a PR to declare a
NotificationCenter
dependency toDependencyValues
. Turns out I was not the first and it exists inswift-dependency-additions
. There was an insightful thread about it on Slack, too.In Brandon's review of my PR (if you're reading, thank you for your time!), he said:
In Stephen's review of the other PR, he said:
In the discussion thread on Slack, others suggested
NotificationCenter.default
did not need to be controlled.Suppose I am testing a handful of features that observe and respond to
UIApplication.didBecomeActiveNotification
. When I build and test the application target, this'll be one of the notifications posted by UIKit on thedefault
NotificationCenter
. So there is, in principle, a race condition. So clearly, I do not have complete control overNotificationCenter.default
. Why wouldn't I want complete control over the dependency by passing an instance of the center for that test case?One solution to this problem would be to make the
NotificationCenter
an implementation detail of a service. But that'd result in a whole lot of boilerplate I'd rather not have to deal with. So I don't think that's a very good alternative.A better solution to this problem could be to realise that
UIApplication.didBecomeActiveNotification
shouldn't be directly observed, e.g.:In this solution, the feature would indirectly observe
testCaseDidBecomeActive
and the test case could post this notification. Then, I could accept this making the need to control the observed center as redundant, even if your app is only ever realistically going to run on one platform.What do you all think? Anything I missed in my reasoning above?
Thanks for your time.
Beta Was this translation helpful? Give feedback.
All reactions