Test Double in Swift - Dummy
Dummy objects are passed around but never actually used. Usually, they are just used to fill parameter lists. e.g.
Type attributes
ormethod parameters
.
Sometimes we need to pass an object just to satisfy language syntax, but we don’t care about its value. We can use dummy arguments whenever a method of the sut(system under test) take objects as arguments and those objects are not relevant to the test.
The simplest implementation of Dummy Object is to pass a null as the parameter.
The biggest disadvantage of using null is that it is not very descriptive.
Clearly communicated to your reads which arguments are dummy arguments. For a
string, this can be done by setting the value to "Dummy"
or ""
, for numbers,
0
is often clear enough. For other types, extract a variable and give it a
name starting with dummy
String arguments
class Greet {
func greeting(_ name: String) -> String {
return "Hello, \(name)"
}
}
func test_greeting_shouldStartWithHello() {
let sut = Greet()
let result = sut.greeting("Dummy")
XCTAssertTrue(result.hasPrefix("Hello,"))
}
Type in Spy
sut
never care theDummyURLSessionDataTask
in Spy, it’s just satisfy theresume()
called by session’s task in production code.
protocol URLSessionProtocol {
func dataTask(
with url: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask
}
var session: URLSessionProtocol = URLSession.shared
let dataTask = session.dataTask(with: url) {
[weak self] (data: Data?, response: URLResponse?, error: Error?)
-> Void in
doSomething()
}
dataTask?.resume()
class SpyURLSession: URLSessionProtocol {
var dataTaskCallCount = 0
var dataTaskArgsURL: [URL] = []
var dataTaskArgsCompletionHandler: [(Data?, URLResponse?, Error?) -> Void] = []
func dataTask(
with url: URL,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void
) -> URLSessionDataTask {
dataTaskCallCount += 1
dataTaskArgsURL.append(url)
dataTaskArgsCompletionHandler.append(completionHandler)
return DummyURLSessionDataTask()
}
}
private class DummyURLSessionDataTask: URLSessionDataTask {
override func resume() { }
}