Skip to content

Instantly share code, notes, and snippets.

@ClaudeHangui
Created May 23, 2021 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ClaudeHangui/ce06cf55148c230c4a3ed11d08e24fd4 to your computer and use it in GitHub Desktop.
Save ClaudeHangui/ce06cf55148c230c4a3ed11d08e24fd4 to your computer and use it in GitHub Desktop.
Unit test for the repostory. When fetching data from the APi the repository should return some result
package com.changui.penguinpay
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.rules.TestRule
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
@ExperimentalCoroutinesApi
class ExchangeRateRepoImplTest {
@get:Rule
val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()
@get:Rule
val testCoroutineRule = TestCoroutineRule()
@get:Rule
val expectedException = ExpectedException.none()
private lateinit var repository: ExchangeRateRepoImpl
@Mock private lateinit var mockApi: RateExchangeApi
@Mock private lateinit var mockNetworkAccessInt: NetworkAccessInt
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
repository = ExchangeRateRepoImpl(mockApi, mockNetworkAccessInt)
}
@Test(expected = InternetErrorException::class)
fun `verify fetching latest exchange rates throws an InternetErrorException when user has no internet access`() {
testCoroutineRule.runBlockingTest {
`when`(mockNetworkAccessInt.isConnectedToInternet()).thenReturn(false)
repository.getExchangeRates()
}
}
@Test(expected = NoDataException::class)
fun `when user has internet access, verify fetching latest exchange rates is a success but throws a NoDataException due to no rates available`() {
testCoroutineRule.runBlockingTest {
`when`(mockNetworkAccessInt.isConnectedToInternet()).thenReturn(true)
`when`(mockApi.getLatestRates()).thenReturn(ExchangeRateDataResponse("", "", "", null,0))
repository.getExchangeRates()
Unit
}
}
@Test
fun `when user has internet access, verify fetching latest exchange rates is a success with rates available`() {
val apiResponse = TestUtils.getApiResponse()
testCoroutineRule.runBlockingTest {
`when`(mockNetworkAccessInt.isConnectedToInternet()).thenReturn(true)
`when`(mockApi.getLatestRates()).thenReturn(apiResponse)
repository.getExchangeRates()
assertNotNull(apiResponse.rates)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment