Consider the following class named SomeClass written in Swift:
#objc class SomeClass: NSObject
{
var shouldCallBar = false
func foo()
{
if (shouldCallBar == true)
{
bar()
}
}
func bar()
{
}
}
For testing the above class foo() method (and similar scenarios mostly written in Objective-C) I was using OCMock like:
- (void) testFooBarShouldBeCalledWhenShouldCallBarIsTrue
{
SomeClass * someClass = [SomeClass new];
// Create mocks.
id mockSomeClass = OCMPartialMock(someClass);
// Expect.
[[mockSomeClass expect] bar];
// Stub.
someClass.shouldCallBar = YES;
// Run code under test.
[someClass foo];
// Verify.
[mockSomeClass verify];
// Stop mocking.
[mockSomeClass stopMocking];
}
But above test fails with Swift code as OCMock won't works well with Swift.
So I am considering something like entirely in Swift:
class SomeClassTests: XCTestCase
{
class MockSomeClass: SomeClass
{
var isBarCalled = false
override func bar()
{
isBarCalled = true
}
}
func testBarShouldBeCalledWhenTrue()
{
let someClass = MockSomeClass()
someClass.shouldCallBar = true
someClass.foo()
XCTAssertTrue(someClass.isBarCalled == true)
}
}
Note here I am subclassing the original class under test and overriding the bar(). I am not at all touching the foo() implementation.
But the downside is I am using MockSomeClass instance to test foo() of SomeClass. This is something I don't like and not recommended.
Is there any better solution to the problem above?
Notes:
I am not talking about Dependency Injection here. Dependency Injection is entirely different approach.
I face these kind of issues when testing UI code in UIViewController.
I have thought of Protocol based programming but was not able to come up with solution to problem above.
So, you want to test that one method (foo) does or does not call another method (bar). The foo method is the one under test, and the bar method is, in the wider sense, a dependent component.
If the invocation of bar has lasting side effects, you could get away with testing that the side effect is/isn't present, maybe by querying a property or similar. In that case you don't need mocks or similar.
If there are no side effects then you must substitute the dependency. To do so you need a seam at which you place code that can tell the test whether the method has been invoked or not. For that, I can only see the two options that Jon already discussed in the question you refer to.
You either put the two methods into separate classes, in which case the class boundary is the seam. Using a protocol, or just an informal convention, you can then completely replace the class that implements bar. Dependency injection comes in handy here.
If the two methods must stay in the same class then you have to use a subclass boundary as a seam, i.e. you use the fact that you can override methods and implement a test-specific sublass. It's easiest when you can use a mock framework. If that's not an option you have to write the code yourself, much like what you describe in your question.
Related
Can we communicate between classes like below code instead of using delegate/protocol pattern and notification. I haven't seen any code example like this. But just curious to know why this should work or not work.
class Class1 {
var class2Obj: Class2 = Class2()
init() {
class2Obj.class1Obj = self
}
func class1Method() {
print("Parent")
}
}
class Class2 {
weak var class1Obj: Class1?
func class2Method() {
class1Obj.class1Method()
}
}
What you have here is a delegate pattern. Your delegate property is merely called class1Obj rather than the more customary delegate name. The key issue here is that you're not using a protocol, and as a result these two classes are "tightly coupled," i.e. Class2 is highly dependent upon details of the Class1 implementation. Furthermore, with these two tightly coupled classes, it's not immediately clear which methods of Class1 that Class2 might need. It makes maintenance of Class1 harder because so it's easy to accidentally make a change that breaks behavior in Class2. It also makes it hard to use Class2 in conjunction with some other class other than Class1.
Instead, you'd generally declare a protocol to precisely articulate the nature of the contract between Class2 and other object that might need to use it. The result is that the classes are less tightly coupled, i.e. Class2 needs to know nothing about the other class other than its conformance to the protocol in question. Furthermore, when editing Class1, if you declare it to conform the the protocol, the compiler will warn you when you fail to implement some required method or property.
So, with a negligible amount of work up-front, the protocol makes the code much easier to maintain. It also provides some additional flexibility whereby you may use Class2 in conjunction with something other than Class1 in the future.
Bottom line, protocols can result in code that is easier to maintain and is more flexible, with no hidden assumptions.
If you don't want to use the delegate-protocol pattern, another alternative is to use a closure, where Class1 supplies a block of code that Class2 can call. So you can do something like:
class Class1 {
var class2Obj = Class2()
init() {
class2Obj.handler = { [weak self] in // note `weak` reference which avoids strong reference cycle
self?.class1Method()
}
}
func class1Method() {
print("Parent")
}
}
class Class2 {
var handler: (() -> Void)?
func class2Method() {
handler?()
}
}
While the delegate-protocol pattern is useful when you have a rich interface between the two classes, this closure pattern when you have a very simple interface between the two classes.
Frankly, a more common permutation of the above is where the closure is more directly associated with some particular request that Class1 initiates in Class2. So, you might just make the parameter a closure to the appropriate method in Class2. Furthermore, you're often passing data back, so imagine that we're passing back an optional String:
class Class1 {
var class2Obj = Class2()
func performClass2Method() {
class2Obj.class2Method { string in
guard let string = string else { return }
self.class1Method()
}
}
func class1Method() {
print("Parent")
}
}
class Class2 {
func class2Method(completionHandler: #escaping (String?) -> Void) {
// do something which creates `string`
// when done, call the closure, passing that `string` value back
completionHandler(string)
}
}
These closure patterns a great way to do simple interfaces between objects, but also keeps the two classes very loosely coupled (i.e. Class2 has no dependencies upon Class1), much like using a protocol in the delegate pattern did. But hopefully the above closure examples illustrate a simple alternatives to the rich delegate-protocol pattern.
I'm looking for suggestions on good practices to test the equality of swift objects
If I have a complex object with many properties it's easy to miss the equality implementation.
What are the good practices to enforce the equality implementation?
More details:
Of course, you can write tests to check that two value are equal when they should, but the problem here is that this can break easily.
You have a struct in your project, after six months another developer adds a property to that struct.
Assume that he forgets to add the property to the equality. The equality still works, the tests pass but your app will break when only that property changes. My question is, there is a way to avoid this problem?
In a non trivial app is really easy to end up having model objects with 10 values, and use nested model objects. So how can I keep under control the equality of my model objects? How can I reduce the human error risk in the equality implementation?
Possible solution:
One solution I have in mind is to write a script that looks at compile time for classes and struct that conform to a certain protocol
Diffable : Equatable {}
For all the classes/structs that adopt Diffable I'll check for the existance of a test file, i.e.:
For the class Foo I'll look for a test class Foo_Tests_Diffable
than for all the properties inside Foo I'll check for the existance of a test function that conform to the following name pattern
test<property name>Diffable
i.e.:
class Foo : Diffable {
var title: String
var color: UIColor
var tag: Tag
}
I'll check for the following tests inside Foo_Tests_Diffable
func testTitleDiffable {
// Test
}
func testColorDiffable {
// Test
}
func testTagDiffable {
// Test
}
If all the script finds all the expected tests than the compile step pass, otherwise it fails
But this solution it's time consuming and I don't know if I'll be able to implement it, so any suggestion is welcome
I would create unit tests specifically for this purpose.
class YourObjectEquatableTests: XCTestCase
{
func testPropertyOne()
{
var object1 = /* ... */
var object2 = /* ... */
object1.propertyOne = nil
object2.propertyOne = nil
XCTAssertEqual(object1, object2)
object1.propertyOne = "different value"
XCTAssertNotEqual(object1, object2)
/* etcetera */
}
func testPropertyTwo()
{
/* ... */
}
}
Note: if you write your test cases before implementing the Equatable details, you're actually doing TDD which is very cool!
I didn't try it a lot but Swift has Reflection capabilities.
https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/
So in your case, you can mirror a class and then put some conditions in your test.
for example, you can set a fix number or attribute or methods for a class in your test.
let nbAttributes = 6
and then check it:
aMirror.children.count
I wrote a simple example in the playground and if I add a method variable, the children count increases. I don't know if it's possible to check the methods though.
class toto{
var io = 9
var tutu = "yo"
func test(){
}
}
let toto1 = toto()
let aMirror = Mirror(reflecting: toto1)
aMirror.children.count
another link:
Reflection in swift 2
Hope that helps :)
Yes, expanding on #Mikael's answer, you should probably use Reflection.
An example would be:
String(reflecting: obj1) == String(reflecting: obj2)
I was under the impression that the main reason for using singletons was to make sure that only one instance could be created in a program. I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
What makes a singleton different than a regular class if it lets you create multiple instances?
// singleton class
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
}
// use
Car.sharedCar.run()
// other instances- I was expecting an error here
var jetta = Car()
jetta.run()
var cobalt = Car()
cobalt.run()
What am I missing here, can someone explain singletons?
I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
There is no language feature called "singleton", it is an idiomatic pattern. If you leave your implementation of singleton open for instantiations from outside, there is nothing the compiler can do about that.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
You should add a private init to make sure there are no external instantiations:
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
private init() {
}
}
Now you are the only one who can instantiate your class. Users of Car class outside of your code are forced to rely on sharedCar instance that you create for them.
I have a complicated view class,
class Snap:UIViewController, UIScrollViewDelegate
{
}
and the end result is the user can, let's say, pick a color...
protocol SnapProtocol:class
{
func colorPicked(i:Int)
}
class Snap:UIViewController, UIScrollViewDelegate
{
someDelegate.colorPicked(blah)
}
So who's going to handle it.
Let's say that you know for sure there is something up the responder chain, even walking through container views, which is a SnapProtocol. If so you can use this lovely code to call it
var r : UIResponder = self
repeat { r = r.nextResponder()! } while !(r is SnapProtocol)
(r as! SnapProtocol).colorPicked(x)
If you prefer, you can use this superlative extension
public extension UIResponder // walk up responder chain
{
public func next<T>() -> T?
{
guard let responder = self.nextResponder()
else { return nil }
return (responder as? T) ?? responder.next()
}
}
courtesy these guys and safely find any SnapProtocol above you,
(next() as SnapProtocol?)?.colorPicked(x)
That's great.
But. What if the object that wants to get the colorPicked is a knight-move away from you, down some complicated side chain, and/or you don't even know which object wants it.
My current solution is this, I have a singleton "game manager" -like class,
public class .. a singleton
{
// anyone who wants a SnapProtocol:
var useSnap:SnapProtocol! = nil
}
Some freaky class, anywhere, wants to eat SnapProtocol ...
class Dinosaur:NSObject, SnapProtocol
{
....
func colorPicked(index: Int)
{...}
... so, to set that as the desired delegate, use the singleton
thatSingleton.useSnap = dinosaur
Obviously enough, this works fine.
Note too that I could easily write a little system in the singleton, so that any number of users of the protocol could dynamically register/deregister there and get the calls.
But it has obvious problems, it's not very "pattern" and seem violently non-idiomatic.
So. Am I really, doing this the right way in the Swift milieu?
Have I indeed confused myself, and there is some entirely different pattern I should be using in today's iOS, to send out such "messages to anyone who wants them?" ... maybe I shouldn't even be using a protocol?
"Send out messages to anyone who wants them" is pretty much the description of NSNotificationCenter.
True, it's not an API that's designed from the beginning for Swift patterns like closures, strong typing, and protocol-oriented programming. (As noted in other comments/answers, the open source SwiftNotificationCenter is a good alternative if you really want such features.)
However, NSNotificationCenter is robust and battle-hardened — it's the basis for thousands of messages that get sent around between hundreds of objects on each pass through the run loop.
Here's a very concise how-to for using NSNotificationCenter in Swift:
https://stackoverflow.com/a/24756761/294884
There is no "protocol based" notification mechanism in the Swift standard
libraries or runtime. A nice implementation can be found here https://github.com/100mango/SwiftNotificationCenter. From the README:
A Protocol-Oriented NotificationCenter which is type safe, thread safe
and with memory safety.
Type Safe
No more userInfo dictionary and Downcasting, just deliver the concrete
type value to the observer.
Thread Safe
You can register, notify, unregister in any thread without crash and
data corruption.
Memory Safety
SwiftNotificationCenter store the observer as a zeroing-weak
reference. No crash and no need to unregister manually.
It's simple, safe, lightweight and easy to use for one-to-many
communication.
Using SwiftNotificationCenter, a (instance of a) conforming class could register itself for example like this:
class MyObserver: SnapProtocol {
func colorPicked(i: Int) {
print("color picked:", i)
}
init() {
NotificationCenter.register(SnapProtocol.self, observer: self)
}
}
and a broadcast notification to all conforming registered observers is
done as
NotificationCenter.notify(SnapProtocol.self) {
$0.colorPicked(x)
}
I am trying a bit of type (aka class) method but am confused on the real world application of such methods. e.g. In the following code from tutorialspoint.com -
class Math
{
class func abs(number: Int) -> Int
{
if number < 0
{
return (-number)
}
else
{
return number
}
}
}
let no = Math.abs(-35)
println(no)
So my question is that what is happening here when I am writing a type method. At what point of my programming may I need this. Can any one explain with a bit clear and simple example.
these kinds of functions are useful when you dont actually need an instance of the type to be made to be able to call it, eg helper methods. take the example you posted, if you call the abs function, you dont really need to make a Math object instantiated to do that (you could be seems unnecessary).
if your abs function wasnt a type method, you would have to go like this
var mathObject = Math()
mathObject.abs(-35)
as apposed to the way you have it in you example
Math.abs(-35)
both statements achieve the same goal, but the 2nd is more elegant (and memory efficient).
there are other reasons as well for using type methods, but this is just the simplest example of one (look up what a singleton is, for another example)
class C {
class func foo(){}
// Type method is always static !!!
static func boo() {}
}
class D: C {
override class func foo() {}
// this is not possible for 'Type method'
override static func boo() {} // error !!!!
}