我希望根据演示者中检查的结果来调用正确的委托方法。
嘲笑我的IdentityProvider
返回true,我该如何编写一个测试来断言delegate?.userIsAuthenticated()
被调用?
import Foundation
import InjectStory
protocol StartPresenterDelegate: class {
func userIsAuthenticated()
func userNeedsToAuthenticate()
}
class StartPresenter {
weak var delegate: StartPresenterDelegate?
weak var view: StartViewInterface!
private lazy var identityProvider = Dependencies.identityProvider.inject()
init(view: StartViewInterface) {
self.view = view
}
private func checkUserAuthState() {
if identityProvider.isAuthorized() {
delegate?.userIsAuthenticated()
} else {
delegate?.userNeedsToAuthenticate()
}
}
}
extension StartPresenter: StartPresentation {
func onViewDidLoad() {
checkUserAuthState()
}
}
extension StartPresenter {
struct Dependencies {
static let identityProvider = Injection<IdentityProviderProtocol>(IdentityProvider.shared)
}
}
答案 0 :(得分:2)
您还必须如下模拟StartPresenterDelegate
。
class MockStartPresenterDelegate: StartPresenterDelegate {
var userIsAuthenticated_wasCalled = false
func userIsAuthenticated() {
userIsAuthenticated_wasCalled = true
}
}
注入MockStartPresenterDelegate
作为代理,并检查userIsAuthenticated_wasCalled
是否为真
答案 1 :(得分:2)
您需要做一些技巧。为您的协议StartPresenterDelegate
创建MockDelegateClass
例如:
class MockDelegate: StartPresenterDelegate {
var isUserIsAuthenticatedCalled = false
var isUserNeedsToAuthenticateCalled = false
func userIsAuthenticated() {
isUserIsAuthenticatedCalled = true
}
func userNeedsToAuthenticate() {
isUserNeedsToAuthenticateCalled = true
}
}
然后在您的测试中尝试执行以下操作:
func test_MyTest() {
// init your class StartPresenter that you wanna test
var presenter = StartPresenter(...)
var mockDelegate = MockDelegate()
presenter.delegate = mockDelegate
presenter.onViewDidLoad()
XCTAssertTrue(mockDelegate.isUserIsAuthenticatedCalled)
XCTAssertFalse(mockDelegate.isUserNeedsToAuthenticateCalled)
// or change isUserIsAuthenticatedCalled and isUserNeedsToAuthenticateCalled if you expect another states
}
对于不同的状态,您需要不同的测试,对您而言,这将是测试委托调用的最简单方法。
答案 2 :(得分:0)