|< Should you write tests as you go or all at the end?||What are the most important things to be tested in an iOS app? >|
Recorded – watch the full episode on YouTube.
What techniques do you use use to make sure the Swift code you’re writing is testable?
Ellen Shapiro: There's definitely some dependency injection. I actually prefer calling it parameterization because dependency injection sounds terrifying. The main thing that dependency injection involves is saying, “okay, instead of using this thing here, I want you to use this fake one.” And one way that you could do this, particularly in Swift, is in the initializer or something. You just add a parameter where you say, “give me something that conforms to this protocol.” And you can give it a default value in Swift so that it uses the real thing 99% of the time. But then when you test it, you can hand it a fake thing.
And I feel like calling it parameterization makes it seem a lot more accessible because it really just puts a note on like, this is what you're doing. Instead of having it be a property, you're having it be a parameter and you can use it to set things up either for production or for testing. And at that point then it makes testing stuff a lot easier.
“There's definitely some dependency injection. I actually prefer calling it parameterization because dependency injection sounds terrifying.”
I think another thing I have found to be helpful that I don’t want to give any kind of guideline in terms of how long should a method be. I know that there's some stuff in Swift land where it yells at you if you have more than 50 lines of code in one method or something like that. But I think the thing that I've found is just sort of like, look at how many different things is this particular method doing, and sort of how many of them are conceptually different versus how many of them are sort of conceptually the same thing. So, for example, there's something where I am getting the SHA256 hash of a file.
There's a bunch of it where it's just, okay, load file. Do this, do that. But you know, ultimately the unit of what I'm doing is, here's a file, give me the SHA256 hash. Most of the stuff that can fail in that is really complicated C stuff. That's really kind of a pain in the butt. And ultimately if I broke that out into smaller pieces, it would just make the calls much more complicated. Honestly some of getting to where do you break this out versus where you leave it as one piece, some of that is just practice.
This transcript was recorded as part of Swiftly Speaking. You can watch the full original episode on YouTube, or subscribe to the audio version on Apple Podcasts.
SPONSORED Check out Stream's cross-platform open source chat SDK on GitHub! Write once and deploy your app with fully featured chat UI on iOS and macOS.
Link copied to your pasteboard.