Dependency injection: static methods and parameters - swift

I am attempting to add unit tests to a Swift program that is layered on an Objective-C library. My main problem at the moment is finding a way to inject a dependency that is created using a parameterized static factory method.
As an example, the following code is functional but rather test-resistant:
class Processor {
var service: RegistrationService?
func register(user: String, pass: String) {
let configuration = Configuration(user: user, pass: pass)
service = RegistrationServiceProvider.registrationService(configuration: configuration)
// Do various things with the 'service'
}
}
Note that RegistrationServiceProvider, RegistrationService, and Configuration are all from the Objective-C library.
What I'd like to be able to do is to provide the RegistrationService that's created in this code as the default and replace it with my own mock when testing. Without the Configuration object that would be fairly simple using something like http://www.danielhall.io/swift-y-dependency-injection-part-two.
(I realize that I could/should push the Configuration construction to the caller, but that doesn't solve the problem of how to supply it to a default service.)
Suggestions and references are welcome.

You can create a mock of both RegistrationService and RegistrationServiceProvider and inject them in the test, using the standard Type as the default type in the normal call, like the code below (it includes example versions of the classes that you use and some printouts to see what is called):
class Configuration {
let user: String
let pass: String
init(user: String, pass: String) {
self.user = user
self.pass = pass
}
}
class RegistrationService {
let configuration: Configuration
init(configuration: Configuration) {
self.configuration = configuration
}
}
class RegistrationServiceProvider {
class func registrationService(configuration: Configuration) -> RegistrationService {
print("Provider instantiated service")
return RegistrationService(configuration: configuration)
}
}
class Processor {
var service: RegistrationService?
func register(user: String, pass: String, serviceProvider: RegistrationServiceProvider.Type = RegistrationServiceProvider.self) {
let configuration = Configuration(user: user, pass: pass)
service = serviceProvider.registrationService(configuration: configuration)
// Do various things with the 'service'
}
}
class MockProvider: RegistrationServiceProvider {
override class func registrationService(configuration: Configuration) -> RegistrationService {
print("Mock provider instantiated mock service")
return MockService(configuration: configuration)
}
}
class MockService: RegistrationService {
override init(configuration: Configuration) {
super.init(configuration: configuration)
print("Mock service initialized")
}
}
let processor = Processor()
processor.register(user: "userName", pass: "myPassword") // Provider instantiated service
processor.register(user: "userName", pass: "myPassword", serviceProvider: MockProvider.self) // Mock provider instantiated mock service

I ended up with a slightly different implementation than the accepted answer above using a protocol instead of inheritance. I don't believe it is a better implementation. Just a personal preference. It does require extra code to define the protocol.
protocol ServiceProvidable {
func registrationService(configuration: Configuration) -> RegistrationService
}
That would change the parameters of the register function to...
func register(user: String, pass: String, serviceProvider: ServiceProvidable.Type = RegistrationServiceProvider.self)
and the provider would conform to the protocol...
class RegistrationServiceProvider: ServiceProvidable
Now your mock providers could simply adhere to the protocol and implement the required function without an override. You also get the added benefit of letting Xcode stub out the function. Not a big deal but a small convenience.
Just a different perspective from a protocol oriented programming style.

Related

Unable to cast to protocol from framework during test cases

So I have a class that comes from one of our internal frameworks. It is defined as follows:
// This lives within a framework
class ExternalClass: ExternalClassProtocol {
// implementation here
}
// This lives within my test target
class MockExternalClass: ExternalClassProtocol {
// Mock implementation here
}
// This lives within the same external frame work as ExternalClass
protocol ExternalClassProtocol: AnyObject {
// Protocol methods here
}
During my test cases, if I try to cast MockExternalClass as? ExternalClassProtocol, the test case crashes.
However, during live app runtime, there is no problem casting ExternalClass as? ExternalClassProtocol.
Is this an issue with trying to implement a protocol from an external module? Is there a way around this?
The class is being accessed through dependency injection (see below dependency injection implementation). The crash occurs on the resolve function.
If you actually debug to this point, you can see that the mock dependency IS in my dependency root (the services array below).
So I know its not failing to cast due to the dependency being missing.
#propertyWrapper
struct Injected<Value> {
var key: String
var wrappedValue: Value {
get { return Dependency.root.resolve(key: self.key) }
set { Dependency.root.add(key: self.key, newValue) }
}
init(key: String) {
self.key = key
}
}
class Dependency {
static let root = Dependency()
var services: [String : Any] = [:]
func add<T>(key: String, _ service: T) {
services[key] = service
}
func resolve<T>(key: String) -> T {
guard let component: T = services[key] as? T else {
// The test crashes here. It works fine on other mocks that are internal to the project
fatalError("Dependency '\(T.self)' not resolved!")
}
return component
}
func clearDependencies() {
self.services.removeAll()
}
private init() {}
}
In my test case:
#testable import MyProject
import ExternalDependency
class TestCase: XCTestCase {
private var subject: ClassWithService!
private var mockInternalClass: MockInternalClassProtocol!
private var mockExternalClass: MockInternallClassProtocol!
func setUp() {
mockExternalClass = MockExternalClass() // This one crashes when trying to cast to its parent protocol
mockInternalClass = MockInternalClass() // This one does not crash when casting to parent protocol.
Dependency.root.add(key: "internal_class", mockInternalClass)
Dependency.root.add(key: "external_class", mockExternalClass)
}
}
Some things I've tried:
Adding AnyObject to the protocol (this fixed a similar issue for internally defined classes that I mock).
changing mockExternalClass type to be the protocol
changing mockExternalClass type to be the implementation
Aside from one protocol being defined in one of our pods, there is no difference between the external protocol and the one we have defined in our own project.
One thing I have noticed is that the cast does not fail if you set a break point inside one of my test case functions. But if you try the same cast within the Dependency.resolve function it crashes. Which leads me to believe there is an issue with the generics.
Any ideas?

How can I verify a class method is called using XCTAssert?

I have a service class, I would like to assert 2 things
A method is called
The correct params are passed to that method
Here is my class
protocol OAuthServiceProtocol {
func initAuthCodeFlow() -> Void
func renderOAuthWebView(forService service: IdentityEndpoint, queryitems: [String: String]) -> Void
}
class OAuthService: OAuthServiceProtocol {
fileprivate let apiClient: APIClient
init(apiClient: APIClient) {
self.apiClient = apiClient
}
func initAuthCodeFlow() -> Void {
}
func renderOAuthWebView(forService service: IdentityEndpoint, queryitems: [String: String]) -> Void {
}
}
Here are my tests
class OAuthServiceTests: XCTestCase {
var mockAPIClient: APIClient!
var mockURLSession: MockURLSession!
var sut: OAuthService!
override func setUp() {
mockAPIClient = APIClient()
mockAPIClient.session = MockURLSession(data: nil, urlResponse: nil, error: nil)
sut = OAuthService(apiClient: mockAPIClient)
}
func test_InitAuthCodeFlow_CallsRenderOAuthWebView() {
let renderOAuthWebViewExpectation = expectation(description: "RenderOAuthWebView")
class OAuthServiceMock: OAuthService {
override func initAuthCodeFlow() -> Void {
}
override func renderOAuthWebView(forService service: IdentityEndpoint, queryitems: [String: String]) {
renderOAuthWebViewExpectation.fulfill()
}
}
}
}
I was hoping to create a local sub class of OAuthService, assign that as my sut and call something like like sut.initAuthCodeFlow() and then assert that my expectation was fulfilled.
I believe this should satisfy point 1. However I cannot access my expectation when attempting to assign it as fulfilled as I get the following error
Class declaration cannot close over value
'renderOAuthWebViewExpectation' defined in outer scope
How can I mark this as fulfilled?
I am following a TDD approach, so I understand my OAuthService would produce a failing test at this point anyway*
I was hoping to create a local sub class of OAuthService, assign that as my sut and call something like like sut.initAuthCodeFlow() and then assert that my expectation was fulfilled.
I would strongly discourage you from using this approach. If your SUT is an instance of the subclass then your test is not truly testing OAuthService, but OAuthService mock.
Moreover, if we think of tests as a tool to:
prevent bugs when code is change
help refactoring and maintenance of the code
then I would argue that testing that calling a certain function calls another function is not a good test. That's harsh, I know, so let me unpack why that's the case.
The only thing it's testing is that initAuthCodeFlow() calls renderOAuthWebView(forService:, queryitems:) under the hood. It doesn't have any assertion on the actual behaviour of the system under test, on the outputs it produces directly or not. If I were to edit the implementation of renderOAuthWebView(forService:, queryitems:) and add some code that would crash at runtime this test would not fail.
A test like this doesn't help with keeping the codebase easy to change, because if you want to change the implementation of OAuthService, maybe by adding a parameter to renderOAuthWebView(forService:, queryitems:) or by renaming queryitems into queryItems to match the capitalization, you'll have to update both the production code and the test. In other words, the test will get in your way of refactoring -changing how the code looks without changing how it behaves- without any extra benefit.
So, how should one test OAuthService in a way that prevents bugs and helps moving fast? The trick is all in testing the behaviour instead of the implementation.
What should OAuthService do? initAuthCodeFlow() doesn't return any value, so we can check for direct outputs, but we can still check indirect outputs, side effects.
I'm making a guess here, but I from your test checking that renderOAuthWebView(forService:, queryitems:) I'd and the fact that it gets an APIClient type as input I'd say it'll present some kind of web view for a certain URL, and then make another request to the given APIClient maybe with the OAuth token received from the web view?
A way to test the interaction with APIClient is to make an assertion for the expected endpoint to be called. You can do it with a tool like OHHTTPStubs or with your a custom test double for URLSession that records the requests it gets and allows you to check them.
As for the presentation of the web view, you can use the delegate patter for it, and set a test double conforming to the delegate protocol which records whether it's called or not. Or you could test at a higher level and inspect the UIWindow in which the test are running to see if the root view controller is the one with the web view.
At the end of the day is all a matter of trade offs. The approach you've taken is not wrong, it just optimizes more towards asserting the code implementation rather than its behaviour. I hope that with this answer I showed a different kind of optimization, one biased towards the behaviour. In my experience this style of testing proves more helpful in the medium-long run.
Create a property on your mock, mutating it's value within the method you expect to call. You can then use your XCTAssertEqual to check that prop has been updated.
func test_InitAuthCodeFlow_CallsRenderOAuthWebView() {
let renderOAuthWebViewExpectation = expectation(description: "RenderOAuthWebView")
class OAuthServiceMock: OAuthService {
var renderOAuthWebViewExpectation: XCTestExpectation!
var didCallRenderOAuthWebView = false
override func renderOAuthWebView(forService service: IdentityEndpoint, queryitems: [String: String]) {
didCallRenderOAuthWebView = true
renderOAuthWebViewExpectation.fulfill()
}
}
let sut = OAuthServiceMock(apiClient: mockAPIClient)
XCTAssertEqual(sut.didCallRenderOAuthWebView, false)
sut.renderOAuthWebViewExpectation = renderOAuthWebViewExpectation
sut.initAuthCodeFlow()
waitForExpectations(timeout: 1) { _ in
XCTAssertEqual(sut.didCallRenderOAuthWebView, true)
}
}

How to mock realm-cocoa in swift

I'm using realm-cocoa for my persistence layer. There is one of the classes depending on realm
class RealmMetaData : AbstractMetaData {
var realm: RealmInterface
var isFirstLaunch: Bool = false
init(realm: RealmInterface = try! Realm()) {
self.realm = realm
let results = realm.objects(MyClass.self)
self.isFirstLaunch = (results.count == 0)
if (self.isFirstLaunch) {
realm.write {
realm.add(MyClass())
}
}
}
// some code
}
protocol RealmInterface {
// using a protocol based approach of mocking
func objects<T: Object>(type: T.Type) -> Results<T>
func write(#noescape block: (() throws -> Void)) throws
func add(object: Object)
}
extension Realm: RealmInterface {
func add(object: Object) { self.add(object, update: false) }
// there is a method for Realm with signature: add(object:Object, update:Bool = false)
// but swift extension dose not permit default function parameter, hence the wrapping
}
Then in my test code, I can write a mocked version of RealmInterface and inject it to the RealmMetaData instance using Constructor Injection.
When implementing the mocked RealmInterface, I found that's very difficult to mock the objects function to return an empty list. Because the return type of the function signature Results<T> is a type provided by the Realm Framework and there is no empty constructor available. Here is where I'm stuck.
That Result<T> is a class with final keyword so I also can't subclass it to use it's private methods to fetch an empty collection.
Thanks in advance!
As I suggested in a comments you can just use an internal in-memory Realm inside your test class and forward all methods that return Result<T> to it.
I end up returning my own protocol instead of results. So I have implementation of this protocol with AnyRealmCollection<T> and the other with just [T] so I easily mock it in tests without any in-memory Realm object.

Swift error when a method has not been called previously

Hi I would like to ask if it is any way to get an error on xCode at compiling, when you are using a class method that needs to call first to another method?
I explain:
class MyClass {
func initializeClass(){
}
func loadConfig() {
}
}
var myClass = MyClass()
myClass.loadConfig() --> Throw Error while coding, the same as you get when you don't implement a required protocol function
Correct way :
myClass.initializeClass().loadConfig()
One way to approach this situation is by using the Proxy Design Pattern. Rather than adding both methods to MyClass, make loadConfig() an instance method of MyClassInitProxy:
public class MyClass {
public class MyClassInitProxy {
let owner:MyClass
public func loadConfig() {
// Do the config work using owner to access MyClass
}
private init(owner:MyClass) {
self.owner = owner
}
}
public func initializeClass() -> MyClassInitProxy {
// Do preparation, then
return MyClassInitProxy(owner:self)
}
}
Now the only way one could call loadConfig is by obtaining MyClassInitProxy through initializeClass() call:
var myClass = MyClass()
myClass.initializeClass().loadConfig()
The short answer is - No, you can't have a compile-time error using this approach.
However if you want to make it impossible for anyone to instantiate your class without having configuration prepared, then just require the configuration as an argument in the initializer. E.g.
class MyClass {
init(config: YourConfigType) {
// do something with the config parameter
}
}
... read config from somewhere and create config variable ...
let x = MyClass(config: config)
And then you have a "compile time error" whenever someone wants to use your class without having config setup initially.

Instantiate class from protocol type

I am writing method which takes a type which conforms to a protocol and instantiates an instance of this class. When I build it, the compiler crashes with a segfault. I appreciate that this points to a compiler bug 99% of the time, but I am interested to see if what I'm trying to do is logically correct or am I just throwing absolute nonsense at the compiler and I shouldn't be surprised to see it crash.
Here is my code
protocol CreatableClass {
init()
}
class ExampleClass : CreatableClass {
required init() {
}
}
class ClassCreator {
class func createClass(classType: CreatableClass.Type) -> CreatableClass {
return classType()
}
}
ClassCreator.createClass(ExampleClass.self)
I also tried to rule out passing a Type as a method parameter as being the root of the problem and the following code also crashes the compiler:
protocol CreatableClass {
init()
}
class ExampleClass : CreatableClass {
required init() {
}
}
let classType: CreatableClass.Type = CreatableClass.self
let instance = classType()
So - is this just a straightforward compiler bug and does what I am trying to do seem reasonable, or is there something in my implementation that is wrong?
Edit:
This can be achieved using generics as shown #Antonio below but unfortunately i believe that isn't useful for my application.
The actual non-dumbed down use-case for doing this is something like
protocol CreatableClass {}
protocol AnotherProtocol: class {}
class ClassCreator {
let dictionary: [String : CreatableClass]
func addHandlerForType(type: AnotherProtocol.Type, handler: CreatableClass.Type) {
let className: String = aMethodThatGetsClassNameAsAString(type)
dictionary[className] = handler()
}
required init() {}
}
I usually do that by defining a generic method. Try this:
class func createClass<T: CreatableClass>(classType: T.Type) -> CreatableClass {
return classType()
}
Update
A possible workaround is to pass a closure creating a class instance, rather than passing its type:
class ClassCreator {
class func createClass(instantiator: () -> CreatableClass) -> (CreatableClass, CreatableClass.Type) {
let instance = instantiator()
let classType = instance.dynamicType
return (instance, classType)
}
}
let ret = ClassCreator.createClass { ExampleClass() }
The advantage in this case is that you can store the closure in a dictionary for example, and create more instances on demand by just knowing the key (which is something in 1:1 relationship with the class name).
I used that method in a tiny dependency injection framework I developed months ago, which I realized it works only for #objc-compatible classes only though, making it not usable for my needs...