Skip to content

Instantly share code, notes, and snippets.

@grumpyshoe
Last active February 15, 2019 10:30
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 grumpyshoe/25e54bcba929ef1b7024d203d7a245f0 to your computer and use it in GitHub Desktop.
Save grumpyshoe/25e54bcba929ef1b7024d203d7a245f0 to your computer and use it in GitHub Desktop.
JUnit-Test example
class MainViewModelTest {
private lateinit var apiService: ApiService
@Rule
@JvmField
var rule: TestRule = InstantTaskExecutorRule()
@Before
fun setUp() {
// mock service
apiService = mock()
// define dagger dependencies
val appComponent = DaggerAppComponent.builder()
.apiModule(object : ApiModule() {
override fun provideApiService(): ApiService {
return apiService
}
})
.build()
// set appComponent
Injector.INSTANCE.set(appComponent)
}
@After
fun tearDown() {
// clear dependencies
Injector.INSTANCE.clear()
}
@Test
fun `get response data | apiService is requested`() {
// init viewModel
val viewModel = MainViewModel()
// trigger action
viewModel.loadData()
// check assertions
verify(apiService, times(1)).getData(any<(JSONArray) -> Unit>(), any<(ANError) -> Unit>())
}
@Test
fun `get response data | success | response is returned`() {
// define mock behavior
doAnswer {
val myArray = JSONArray()
myArray.put("test")
val successLambda = it.arguments[0] as (JSONArray) -> Unit
successLambda(myArray)
null
}.whenever(apiService).getData(any<(JSONArray) -> Unit>(), any())
// init viewModel
val viewModel = MainViewModel()
// trigger action
viewModel.loadData()
// check assertions
assertEquals("test", viewModel.data.value)
}
@Test
fun `get response data | error | '-no data -' is returned`() {
// define mock behavior
doAnswer {
val errorLambda = it.arguments[1] as (ANError) -> Unit
errorLambda.invoke(ANError("test message"))
}.whenever(apiService).getData(any(), any<(ANError) -> Unit>())
// init viewModel
val viewModel = MainViewModel()
// trigge action
viewModel.loadData()
// check assertions
assertEquals("- no data -", viewModel.data.value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment