RxSwift Driver got fatal error in Swift Testing because it is not called form main thread.

Hi,

I'm trying the new Swift Testing instead of XCTest for my new project. I am using RxSwift+UIKit. And when I am trying to test my ViewModel that has a Driver in it, it crashes due to the driver is not being called form main thread.

Thread 5: Fatal error: `drive*` family of methods can be only called from `MainThread`.

Here is the test code:

struct PlayerViewModelTest {
@Test func testInit_shouldPopulateTable_withEmpty() async throws {
// Arrange
let disposeBag = DisposeBag()
var expectedSongTableCellViewData: [SongTableCellViewData]?
// Act
let sut = PlayerViewModel(provideAllSongs: { return .just(mockSongList) },
provideSongByArtist: { _ in return .just(mockSongList) },
disposeBag: disposeBag)
sut.populateTable
.drive(onNext: { expectedSongTableCellViewData = $0 })
.disposed(by: disposeBag)
// Assert
#expect(expectedSongTableCellViewData != nil, "Should emit something so it should not be nil")
#expect(expectedSongTableCellViewData!.isEmpty, "Should emit empty array")
}
}

This never happen in XCTest. So I assume Swift Testing is not being run in the main thread? How do I fix this?

Thanks

If an API you use in your @Test function can only be used safely from the main actor, add @MainActor to the @Test function or its containing suite type (struct PlayerViewModelTest, in your case).

Generally, APIs which have this requirement should themselves be annotated with @MainActor and should produce compiler diagnostics giving you a hint about this. If that's not the case, I suggest filing an issue with the maintainers of the library in question (e.g. RxSwift).

RxSwift Driver got fatal error in Swift Testing because it is not called form main thread.
 
 
Q