Learning Unit testing on android, my tests are not running now, says "Test events were not received, not much details on the stack trace I tried adding and removing some dependencies but did not worked. looked into some other stackoverflow results still not working, I am doing this by following a udemy course on TDD.
Here is one of my test classes
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import petros.efthymiou.groovy.utils.BaseUnitTest
import petros.efthymiou.groovy.utils.getValueForTest
class PlayListViewModelShould:BaseUnitTest() {
private val repository: PlayListRepository = mock()
private val playList = mock<List<PlayList>>()
private val expected = Result.success(playList)
private val exception = java.lang.RuntimeException("SOMETHING NOT RIGHT")
#OptIn(ExperimentalCoroutinesApi::class)
#Test
suspend fun getPlaylistsFromRepository()= runTest{
val viewModel = mockSuccesfulCase()
viewModel.playlists.getValueForTest()
verify(repository,times(1)).getPlaylists()
}
#OptIn(ExperimentalCoroutinesApi::class)
#Test
fun emitPlaylistsFromRepository()= runTest {
val viewModel = mockSuccesfulCase()
assertEquals(expected, viewModel.playlists.getValueForTest())
}
#OptIn(ExperimentalCoroutinesApi::class)
#Test
fun emitErrorWhenRecieveError() {
runTest {
whenever(repository.getPlaylists()).thenReturn(
flow {
emit(Result.failure<List<PlayList>>(exception))
}
)
}
val viewModel = PlayListViewModel(repository)
assertEquals(java.lang.RuntimeException("another error"), viewModel.playlists.getValueForTest()!!.exceptionOrNull())
}
private fun mockSuccesfulCase(): PlayListViewModel {
runBlocking {
whenever(repository.getPlaylists()).thenReturn(
flow {
emit(expected)
}
)
}
return PlayListViewModel(repository)
}
}
My gradle
android {
compileSdkVersion 30
defaultConfig {
applicationId "petros.efthymiou.groovy"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
testOptions {
execution 'ANDROIDX_TEST_ORCHESTRATOR'
unitTests.all {
useJUnitPlatform()
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs = freeCompilerArgs + "-Xallow-result-return-type"
}
testOptions {
animationsDisabled = true
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.0-alpha04'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
// testImplementation 'com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0'
testImplementation 'org.mockito:mockito-inline:2.21.0'
testImplementation 'androidx.arch.core:core-testing:2.1.0'
testImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.8'
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.1")
testImplementation 'org.mockito.kotlin:mockito-kotlin:4.0.0'
testImplementation "org.mockito:mockito-core:4.3.1"
androidTestImplementation "org.mockito:mockito-android:3.10.0"
testImplementation 'org.junit.jupiter:junit-jupiter-engine:5.9.1'
testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.1'
androidTestImplementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation "org.mockito:mockito-core:4.3.1"
androidTestImplementation 'junit:junit:4.13.2'
androidTestImplementation "org.robolectric:robolectric:4.3.1"
androidTestImplementation('com.schibsted.spain:barista:3.6.0') {
exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
}
}
Related
I am working on Junit4Test. I am getting an error on default unit test. I run it before working on further but it shows same error even I add the code so I am wondering if someone can help me with this error.
Unite test code
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
#RunWith(AndroidJUnit4::class)
class CrimeDetailFragmentTest {
/*#Test
fun useFragmentContext() {
// Context of the app under test.
val fragmentContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.bignerdranch.android.criminalintent.CrimeDetailFragment", fragmentContext.packageName)
}*/
#Before
fun setUp() {
}
#After
fun tearDown() {
}
}```
build.gradle
android {
compileSdk 32
defaultConfig {
applicationId "com.bignerdranch.android.criminalintent"
minSdk 22
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures{
viewBinding true
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.fragment:fragment-ktx:1.5.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.junit.jupiter:junit-jupiter'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
debugImplementation "androidx.fragment:fragment-testing:1.5.1"
}```
enter image description here
I do not have file called index.xml in my android studio.
I am trying to call a suspend function using viewModelScope.launch in which "launch" is showing as Unresolved reference.
Here is build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.mynotes"
minSdk 27
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
}
dependencies {
implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
implementation "androidx.activity:activity-ktx:$rootProject.activityVersion"
// Dependencies for working with Architecture components
// You'll probably have to update the version numbers in build.gradle (Project)
// Room components
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion"
// Kotlin components
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
// UI
implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion"
implementation "com.google.android.material:material:$rootProject.materialVersion"
// Testing
testImplementation "junit:junit:$rootProject.junitVersion"
androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion"
androidTestImplementation ("androidx.test.espresso:espresso-core:$rootProject.espressoVersion", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation "androidx.test.ext:junit:$rootProject.androidxJunitVersion"
}
and the ViewModel.kt
package com.example.mynotes
import android.app.Application
//import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.*
class NotesViewModel(application: Application) : ViewModel() {
private val repository : NotesRepository
val allNotes : LiveData<List<Notes>>
init {
val dao = NotesDatabase.getDatabase(application).getNotesDao()
repository = NotesRepository(dao)
allNotes = repository.allNotes
}
fun deleteNotes(notes: Notes) = viewModelScope.launch(Dispatchers.IO) {
repository.delete(notes)
}
}
In the function deleteNotes "viewModelScope.launch" is showing Unresolved reference: launch but there is no error while building the app but my app crash while running.
I think it's because of the way you are declaring the variable, since you are declaring it as a direct function, you can try the following:
fun deleteNotes(notes: Notes) {
viewModelScope.launch(Dispatchers.IO) {
repository.delete(notes)
}
}
It's possible the issue is related that when the method is declared and stored in memory, the scope hasnt been assigned yet.
Which version are you using?
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
Try to use this case is different.
Try to invalide cache and restart if still not recognized
I'm trying to call the await() function in the
bookList = bookViewModel.getBookList().await()
in the Main Activity but it gives the error in the header.
Main Activity
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val bookViewModel: BookViewModel by viewModels()
private var bookList : BookList? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GlobalScope.launch(Dispatchers.IO) {
bookList = bookViewModel.getBookList().await()
}
setContent {
LOTRAppTheme {
}
}
}
}
ViewModel
package com.example.lotrapp
import androidx.lifecycle.ViewModel
import com.example.lotrapp.models.BookList
import com.example.lotrapp.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
#HiltViewModel
class BookViewModel #Inject constructor(
private val repository: BookRepository
) : ViewModel() {
suspend fun getBookList() : BookList? {
return repository.getBookList()
}
}
Repository
package com.example.lotrapp.repository
import com.example.lotrapp.models.BookList
import com.example.lotrapp.network.RetrofitApi
import javax.inject.Inject
class BookRepository #Inject constructor(
private val retrofitApi: RetrofitApi
) {
suspend fun getBookList() : BookList?
{
return retrofitApi.getBookList().body()
}
}
Api
package com.example.lotrapp.network
import com.example.lotrapp.models.BookList
import retrofit2.Response
import retrofit2.http.GET
interface RetrofitApi {
#GET("book")
suspend fun getBookList() : Response<BookList>
}
Gradle:
plugins {
id 'com.android.application'
id 'kotlin-android'
id("dagger.hilt.android.plugin")
id("kotlin-kapt")
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.lotrapp"
minSdk 21
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.5.10'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
def compose_version = "1.0.2"
def lifecycle_version = "2.3.1"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
// Lifecycles only (without ViewModel or LiveData)
implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version")
// Saved state module for ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
// Annotation processor
kapt("androidx.lifecycle:lifecycle-compiler:$lifecycle_version")
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version")
implementation 'androidx.activity:activity-compose:1.3.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//Hilt
implementation("com.google.dagger:hilt-android:2.38.1")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")
//Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2")
}
kapt {
correctErrorTypes true
}
First I want to pull the list from the api and then show it in the UI with a Composable function (with LazyColumn) in setContent. It is enough to solve this error, but if you have better code suggestions, I would appreciate it. Thank you!
It doesn't really seem you need to invoke await() there. getBookList() returns BookList? directly, so just remove await() and it should be fine.
Additionally, you said you need to use this bookList in setContent. In that case you need to move setContent into launch block, below getBookList(). Right now setContent really executes before bookList is acquired. It is hard to provide more details without the full contents of setContent.
I am trying to write the following unit test for a function in my project
import android.content.Context
import org.junit.Test
import androidx.test.core.app.ApplicationProvider
import com.adi_random.tracky.api.searchBook
import com.adi_random.tracky.models.GoodreadsBook
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import com.google.common.truth.Truth.assertThat
/**
* Created by meadi on 6/27/2020.
*/
class BookFetchTest {
/**
* Test if the Tracy API searchBook endpoint returns the expected result and gets parsed correctly
*/
val context = ApplicationProvider.getApplicationContext<Context>()
#Test
fun bookFetchResultValidation() {
val query = "Dune";
searchBook(query, context, object : Callback {
override fun onFailure(call: Call, e: IOException) {
TODO("Not yet implemented")
}
override fun onResponse(call: Call, response: Response) {
val gson = Gson();
val res = gson.fromJson<Array<GoodreadsBook>>(
response.body?.charStream(),
Array<GoodreadsBook>
::class.java
)
assertThat(res).hasLength(20);
}
})
}
}
When hitting run, I am getting Unresolved reference in :app:compileDebugUnitTestKotlin gradle task for the following dependencies: test (double clicking the error highlights androidx.test.core.app.ApplicationProvider), common ( in com.google.common.truth.Truth.assertThat), ApplicationProvider ( in ApplicationProvider.getApplicationContext()) and assertThat (in the assertThat call at the end of the test).
Here is my module build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
buildFeatures {
viewBinding true
}
testOptions {
unitTests.includeAndroidResources = true
}
defaultConfig {
applicationId "com.adi_random.tracky"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
useLibrary 'android.test.runner'
useLibrary 'android.test.base'
useLibrary 'android.test.mock'
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.squareup.okhttp3:okhttp:4.1.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment-ktx:2.1.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.1.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'com.google.truth:truth:0.42'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test:core:1.2.0'
// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
}
As you can see I have those dependencies added to my gradle build file with the androidTestImplementation directive, so I don't understand why those errors get thrown. Does anyone have any idea? Thanks in advance!
Edit:Here is a screenshot of the problem:
Add this dependency:
def androidx_test_core = "1.2.0"
androidTestImplementation "androidx.test:core-ktx:$androidx_test_core"
def androidx_test_ext = "1.1.1"
androidTestImplementation "androidx.test.ext:junit-ktx:$androidx_test_ext"
def hamcrestVersion = '2.2'
testImplementation "org.hamcrest:hamcrest:$hamcrestVersion"
I am making some unit testing. but when i want to run that unit test it gave me error like this
"java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)"
what i am doing wrong?
this is my gradle. i wonder if i add wrong dependency into it, please help me :'(
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
multiDexEnabled true
applicationId "com.example.androidjetpacksubmission1"
minSdkVersion 15
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug{
applicationIdSuffix ".debug"
debuggable true
}
}
testOptions {
unitTests.returnDefaultValues = true
}
androidExtensions {
experimental = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'com.github.bumptech.glide:glide:4.10.0'
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
implementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
implementation 'com.facebook.shimmer:shimmer:0.5.0'
implementation "androidx.arch.core:core-testing:2.1.0"
implementation "org.mockito:mockito-android:3.1.0"
implementation 'androidx.multidex:multidex:2.0.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:core:1.2.0'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
androidTestImplementation 'com.google.truth:truth:0.42'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'
androidTestImplementation 'com.android.support.test:runner'
androidTestImplementation group: 'org.mockito', name: 'mockito-core', version: '3.1.0'
androidTestImplementation group: 'org.mockito', name: 'mockito-inline', version: '3.1.0'
testImplementation "androidx.arch.core:core-testing:2.1.0"
androidTestImplementation "org.mockito:mockito-android:3.1.0"
androidTestImplementation "androidx.arch.core:core-testing:2.1.0"
}
and this is my unit test code
package com.example.androidjetpacksubmission1.ui.detail
import androidx.lifecycle.Observer
import com.example.androidjetpacksubmission1.data.entity.TvShowEntity
import com.example.androidjetpacksubmission1.data.repository.RemoteRepository
import com.example.androidjetpacksubmission1.network.Network
import com.example.androidjetpacksubmission1.network.NetworkListener
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
class DetailTvShowViewModelTest : NetworkListener {
override fun onSuccess(msg: String) {
}
override fun onFailure(msg: String?) {
}
#get:Rule
var executorRule = androidx.arch.core.executor.testing.InstantTaskExecutorRule()
private lateinit var detailTvShowViewModel: DetailTvShowViewModel
private lateinit var remoteRepository: RemoteRepository
private lateinit var observer: Observer<*>
private val tvShowTitleExample = "Jumanji: The Next Level"
#Before
fun setup(){
observer = mock(Observer::class.java)
remoteRepository = RemoteRepository(Network.routes())
detailTvShowViewModel = DetailTvShowViewModel(remoteRepository,tvShowTitleExample)
detailTvShowViewModel.networkListener = this
}
#Test
fun getDetailMovie() {
detailTvShowViewModel.getDetailTvShow().observeForever(observer as Observer<in TvShowEntity>)
detailTvShowViewModel.fetchDetailTvShow()
verify(observer).onChanged()
}
}
private fun <T> Observer<T>.onChanged() {
}