Код: Выделить всё
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>
Кроме того, если я изменю объект < /p>
myRepository to myRepository=mockk (relaxed=true)
< /p>
Другой пример: < /p>
Kotlin Code: < /p>
Код: Выделить всё
class TestSample @Inject constructor(
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
@ApplicationScope private val scope: CoroutineScope,
val userRepository: TestUserRepository
) {
suspend fun fetchData(): String {
println(11)
val ret = userRepository.getCurrentUser()
println(22)
return ret
}
}
class TestUserRepository @Inject constructor(
@DefaultDispatcher private val dispatcher: CoroutineDispatcher,
@ApplicationScope private val scope: CoroutineScope,
){
suspend fun getCurrentUser():String{
delay(100)
return ""
}
}
< /code>
ut Code: < /p>
class TestSampleTest {
private lateinit var testSample: TestSample
private lateinit var userRepository: TestUserRepository
private val dispatcher = StandardTestDispatcher()
private lateinit var scope: CoroutineScope
@Before
fun setUp() {
userRepository = mockk(relaxed = true)
scope = TestScope(dispatcher)
scope = CoroutineScope(dispatcher + SupervisorJob())
testSample = TestSample(dispatcher, scope, userRepository)
}
@After
fun tearDown() {
scope.cancel()
}
@Test
fun test() = runBlocking {
val expectResult = "result"
coEvery { userRepository.getCurrentUser() }.returns(expectResult)
val actualResult = testSample.fetchData()
assertEquals(actualResult, expectResult)
}
}
< /code>
userRepository.getCurrentUser()Подробнее здесь: https://stackoverflow.com/questions/792 ... with-mockk
Мобильная версия