Kotlin Code: < /p>
Code: Select all
class MyRepository @Inject constructor(
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
@ApplicationScope private val scope: CoroutineScope,
val checkService:ICheckService = CheckService()
) {
fun fetchData(value: Int): String {
return runBlocking(dispatcher) {
suspendCoroutine { continuation ->
println(111)
scope.launch(dispatcher) {
println(222)
delay(100)
println(333)
if(checkService.check(value)){
println(444)
}
continuation.resume("result")
}
}
}
}
}
interface ICheckService {
suspend fun check(value:Int): Boolean
}
class CheckService:ICheckService{
override suspend fun check(value: Int): Boolean {
// mock delay
delay(300)
return value > 0
}
}
< /code>
UT -Code: < /p>
class MyRepositoryTest4 {
private lateinit var myRepository: MyRepository
private val dispatcher = StandardTestDispatcher()
private lateinit var scope: TestScope
@Before
fun setUp() {
scope = TestScope(dispatcher)
myRepository = MyRepository(dispatcher, scope)
}
@Test
fun testMyRepository1() = scope.runTest {
withContext(Dispatchers.IO){
myRepository.fetchData(-1)
}
}
@Test
fun testMyRepository2() = scope.runTest {
withContext(Dispatchers.IO){
myRepository.fetchData(1)
}
}
}
< /code>
Zusätzlich ändere ich das Objekt von < /p>
myRepository to myRepository=mockk (relaxed=true)
