Created
April 22, 2022 05:18
-
-
Save 1jGabriel/2df7523b5eaa656988f431713ed5e690 to your computer and use it in GitHub Desktop.
Testando Flows =)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestandoSharedFlow(val useCase: TestandoSharedFlowUseCase) : ViewModel() { | |
private val states = MutableSharedFlow<Int>( | |
onBufferOverflow = BufferOverflow.DROP_LATEST, | |
extraBufferCapacity = 1 | |
) | |
fun observeStates() = states.asSharedFlow() | |
fun addToStates(number: Int) { | |
viewModelScope.launch { | |
val resultado = useCase.somaUmAoNumeroRecebido(number) | |
states.emit(resultado) | |
} | |
} | |
} | |
class TestandoSharedFlowUseCase { | |
suspend fun somaUmAoNumeroRecebido(number: Int): Int { | |
val teste = number | |
withContext(Dispatchers.IO) { | |
teste + 1 | |
} | |
return teste | |
} | |
} | |
@RunWith(JUnit4::class) | |
class TestandoSharedFlowTest { | |
val useCase: TestandoSharedFlowUseCase = mockk() | |
val minhaClasse = TestandoSharedFlow(useCase) | |
@Before | |
fun init() { | |
Dispatchers.setMain(UnconfinedTestDispatcher()) | |
MockKAnnotations.init(this) | |
} | |
@After | |
fun tearDown() { | |
Dispatchers.resetMain() // reset the main dispatcher to the original Main dispatcher | |
} | |
@Test | |
fun `testando a emissao dos valores`() = runTest { | |
// setup | |
val list = mutableListOf<Int>() | |
coEvery { useCase.somaUmAoNumeroRecebido(1) } returns 2 | |
coEvery { useCase.somaUmAoNumeroRecebido(2) } returns 3 | |
coEvery { useCase.somaUmAoNumeroRecebido(3) } returns 4 | |
// convert os states em uma lista de emissões | |
val job = launch(UnconfinedTestDispatcher(testScheduler)) { | |
minhaClasse.observeStates().toList(list) | |
} | |
// roda os cenários | |
minhaClasse.addToStates(1) | |
minhaClasse.addToStates(2) | |
minhaClasse.addToStates(3) | |
minhaClasse.addToStates(3) | |
runCurrent() // resume as threads de emissao | |
assertTrue(list[0] == 2) | |
assertTrue(list[1] == 3) | |
assertTrue(list[2] == 4) | |
assertTrue(list[3] == 4) | |
// faz os asserts e para de observar o job lançado anteriormente | |
job.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment