Skip to content

Instantly share code, notes, and snippets.

@takasek
Created September 28, 2018 04:58
Show Gist options
  • Save takasek/adf8610be4d70be6519fc7c10e58912c to your computer and use it in GitHub Desktop.
Save takasek/adf8610be4d70be6519fc7c10e58912c to your computer and use it in GitHub Desktop.
RxTest, TestSchedulerによるテスト例
import RxSwift
import RxCocoa
import RxTest
struct LoginData: Equatable {
let id: Int
}
protocol LoginRepository {
func post(data: LoginData) -> Single<Account>
}
struct Account {}
final class LoginUseCase {
enum Status {
case loggingIn, failed, succeeded
}
private let repository: LoginRepository
private let statusRelay = BehaviorRelay<Status?>(value: nil)
var status: Observable<Status?> { return statusRelay.asObservable() }
private let disposeBag = DisposeBag()
init(repository: LoginRepository) {
self.repository = repository
}
func send(_ data: LoginData) {
statusRelay.accept(.loggingIn)
repository.post(data: data).subscribe(
onSuccess: { _ in self.statusRelay.accept(.succeeded) },
onError: { _ in self.statusRelay.accept(.failed) }
)
.disposed(by: disposeBag)
}
}
final class LoginUseCaseTests: XCTestCase {
func testStatus() {
let scheduler = TestScheduler(initialClock: 0)
let validData = LoginData(id: 1)
let invalidData = LoginData(id: 0)
struct MockRepository: LoginRepository {
struct Error: Swift.Error {}
let scheduler: TestScheduler
let validData: LoginData
func post(data: LoginData) -> Single<Account> {
if data == validData {
return Single.just(Account()).delay(100, scheduler: scheduler)
} else {
return Single.just(Account()).delay(100, scheduler: scheduler).flatMap { _ in Single.error(Error()) }
}
}
}
let repo = MockRepository(scheduler: scheduler, validData: validData)
let useCase = LoginUseCase(repository: repo)
scheduler.scheduleAt(1000, action: { useCase.send(invalidData) })
scheduler.scheduleAt(2000, action: { useCase.send(validData) })
let res: TestableObserver<LoginUseCase.Status?> = scheduler.start(disposed: 50_000) {
return useCase.status.asObservable()
}
print(res.events)
XCTAssertEqual(res.events, [
next(200, nil),
next(1000, .loggingIn),
next(1100, .failed),
next(2000, .loggingIn),
next(2100, .succeeded),
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment