【发布时间】:2015-01-23 18:04:07
【问题描述】:
我正在尝试对依赖于另一个类的方法进行单元测试。该方法调用该类上的类方法,本质上是这样的:
func myMethod() {
//do stuff
TheirClass.someClassMethod()
}
使用依赖注入技术,我希望能够用模拟替换“TheirClass”,但我不知道如何做到这一点。有什么方法可以传入一个模拟类(不是实例)吗?
编辑:感谢您的回复。也许我应该提供更多细节。我试图模拟的类方法在一个开源库中。
下面是我的方法。我正在尝试对其进行测试,同时模拟对NXOAuth2Request.performMethod 的调用。此类方法发出网络调用以从我们的后端获取经过身份验证的用户信息。在关闭中,我将此信息保存到开源库提供的全局帐户存储中,并发布成功或失败的通知。
func getUserProfileAndVerifyUserIsAuthenticated() {
//this notification is fired when the refresh token has expired, and as a result, a new access token cannot be obtained
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didFailToGetAccessTokenNotification", name: NXOAuth2AccountDidFailToGetAccessTokenNotification, object: nil)
let accounts = self.accountStore.accountsWithAccountType(UserAuthenticationScheme.sharedInstance.accountType) as Array<NXOAuth2Account>
if accounts.count > 0 {
let account = accounts[0]
let userInfoURL = UserAuthenticationScheme.sharedInstance.userInfoURL
println("getUserProfileAndVerifyUserIsAuthenticated: calling to see if user token is still valid")
NXOAuth2Request.performMethod("GET", onResource: userInfoURL, usingParameters: nil, withAccount: account, sendProgressHandler: nil, responseHandler: { (response, responseData, error) -> Void in
if error != nil {
println("User Info Error: %@", error.localizedDescription);
NSNotificationCenter.defaultCenter().postNotificationName("UserCouldNotBeAuthenticated", object: self)
}
else if let data = responseData {
var errorPointer: NSError?
let userInfo = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &errorPointer) as NSDictionary
println("Retrieved user info")
account.userData = userInfo
NSNotificationCenter.defaultCenter().postNotificationName("UserAuthenticated", object: self)
}
else {
println("Unknown error retrieving user info")
NSNotificationCenter.defaultCenter().postNotificationName("UserCouldNotBeAuthenticated", object: self)
}
})
}
}
【问题讨论】:
-
依赖注入,你的类应该有一个接受
TheirClass的构造函数。 -
我如何传递一个类和一个类的实例?
-
构造函数应该接受一个实例,您将在其中传递模拟对象。
-
我不能使用模拟实例,因为我必须在真实对象上调用的方法是类方法,而不是实例方法。
-
如果类方法没有全局状态或产生副作用,那么只需专注于对静态方法进行单元测试,您就不需要在
myMethod内部对其进行测试。 programmers.stackexchange.com/questions/5757/…