gpt4 book ai didi

ios - 我如何断言在我的单元测试中调用了委托(delegate)

转载 作者:搜寻专家 更新时间:2023-11-01 06:11:51 24 4
gpt4 key购买 nike

我希望根据演示者的检查结果调用正确的委托(delegate)方法。

在模拟了我的 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)
}
}

最佳答案

你需要做一些技巧。为您的协议(protocol)创建 MockDelegateClass StartPresenterDelegate示例:

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
}

对于不同的状态你需要不同的测试,对你来说这将是测试委托(delegate)调用最简单的方法。

关于ios - 我如何断言在我的单元测试中调用了委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569060/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com