API冲突-多次调用-[xctestexpectations fulfill],我该如何解决这个问题?



我正在为我的代码编写单元测试,使用组合框架

我有一个异步操作,所以我使用expectation(descrption:)等待异步操作

这是我的代码示例

class MyViewModel {
private var someOtherSubject: CurrentValueSubject<...>(...)
var someOtherStream: ... { 
return someOtherSubject.eraseToAnyPublisher()
}

init(...) { 
.
.
bind()
}
private func bind() { 
. 
.
.
someOfMySubject
.flatMap { someAsyncOperation }
.sink { [weak self] ... in 
self?.someOtherSubject.send(value2)
}
.store(..)
}
.
.
func handleSomeUserAction() {
self.someOtherSubject.send(value1)
self.someOfMySubject.send(someEvent)
}
}

我试图检查someOtherStream发出的值,当handleSomeUserAction被称为

所以我写了这样的测试代码

func test_handleSomeUserAction() { 
// given 
let expectation = expectation(description: "...")
var result: ValueType?
// when 
sut.someOtherStream
.dropFirst() // drop CurretValueSubject's default value
.sink { 
result = $0
expectation.fulfill()
}
.store(...)
sut.handleSomeUserAction()
// then
wait(for: [expectation], timeout: 1.0)
let unwrapped = try XCTUnwrap(result)
XCTAssertEqual(unwrapped, value1)
}

我知道expectedFulfillmentCount是1,因为它的默认值是1

但是测试失败了,Xcode显示了这个消息

API冲突-多次调用-[xctestexpectations fulfill]

所以我试着调试,我发现expectation.fulfill()调用了两次,尽管expectedFulfillmentCount是1

和结果是value2不是value1,我期望

为什么会这样?我认为异步操作(flatMap {...})完成得太快,fulfill被调用了两次。

我尝试了延迟模拟方法,但我认为这不是正确的解决方案

你的代码有点奇怪。但是看起来您正在向someOtherStream发送两个值。因此,预计会调用两次接收器。