Mockito может только издеваться над не-частными и нефинальными классами, но основная причина этой ошибки может быть другAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Mockito может только издеваться над не-частными и нефинальными классами, но основная причина этой ошибки может быть друг

Сообщение Anonymous »

Я хочу написать некоторые тесты пользовательского интерфейса для композиционного экрана.
Я постоянно сталкиваюсь с той же ошибкой снова и снова. ViewModel нельзя высмеивать, хотя я объявил класс ViewModel как открытый. < /P>
Вот тестовый код: < /p>
class ReportScreenKtTest {

@get:Rule
val composeTestRule = createComposeRule()

@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()

@Mock
private lateinit var viewModel: ReportViewModel

@Before
fun setUp() {
whenever(viewModel.errorFlow).thenReturn(MutableSharedFlow())
}

@Test
fun contentState_whenCheckPerformWorkoutCheckBox_addsUpdateCheckBox() {
// given
whenever(viewModel.uiState).thenReturn(
MutableStateFlow(ReportState.Content(
date = 0,
dailyReport = report,
cardios = cardios,
cheatMeals = cheatMeals,
notes = notes))
)

composeTestRule.setContent {
AppSurface {
ReportScreen(viewModel = viewModel, navigateToWorkout = {}, navigateBack = {}, navigateToBodyMeasurement = {})
}
}

// when
composeTestRule.onNodeWithTag(ReportScreenConstants.WORKOUT_CHECK_BOX).performClick()

// then
verify(viewModel).add(ReportEvent.UpdateCheckBox(false, CheckBoxField.Workout))
}
< /code>
И вот мой класс ViewModel: < /p>
open class ReportViewModel @Inject constructor(
getDailyReport: GetDailyReport,
private val deleteReport: DeleteDailyReport,
private val updateReport: UpdateDailyReport,
private val savedStateHandle: SavedStateHandle,
// othet use cases
): BlocViewModel() {

// events, state, etc
}
< /code>
Я всегда получаю эту ошибку: < /p>
rg.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class com.example.fitness_routine.presentation.ui.screen.report.ReportViewModel.

Mockito can only mock non-private & non-final classes, but the root cause of this error might be different.
Please check the full stacktrace to understand what the issue is.
If you're still not sure why you're getting this error, please open an issue on GitHub.

IMPORTANT INFORMATION FOR ANDROID USERS:

The regular Byte Buddy mock makers cannot generate code on an Android VM!
To resolve this, please use the 'mockito-android' dependency for your application:
https://search.maven.org/artifact/org.m ... to-android

Java : 0.9
JVM vendor name : The Android Project
JVM vendor version : 2.1.0
JVM name : Dalvik
JVM version : 0.9
JVM info : null
OS name : Linux
OS version : 6.6.30-android15-7-gbb616d66d8a9-ab11968886
< /code>
Есть мысли? < /p>
Вот мой файл Gradle: < /p>
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id("com.google.dagger.hilt.android")
id("com.google.devtools.ksp")
id("com.google.gms.google-services")
}

android {
namespace "com.example.fitness_routine"
compileSdk 34

defaultConfig {
applicationId "com.example.fitness_routine"
minSdk 26
targetSdk 34
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}

ksp {
arg('room.schemaLocation', "$projectDir/schemas")
}

buildFeatures {
buildConfig = true

}
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.5.3'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}

dependencies {

implementation 'androidx.core:core-ktx:1.13.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.7.0'
implementation 'androidx.activity:activity-compose:1.9.0'
implementation platform('androidx.compose:compose-bom:2024.05.00')
implementation 'androidx.compose.ui:ui-graphics'
implementation 'androidx.compose.ui:ui-tooling-preview'
implementation 'androidx.compose.material3:material3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation platform('androidx.compose:compose-bom:2024.05.00')
androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
debugImplementation 'androidx.compose.ui:ui-tooling'
debugImplementation 'androidx.compose.ui:ui-test-manifest'

implementation "androidx.navigation:navigation-compose:2.7.7"

// dagger hilt
def hilt = "2.50"
implementation("com.google.dagger:hilt-android:$hilt")
ksp("com.google.dagger:hilt-compiler:$hilt")

// hilt navigation compose
implementation("androidx.hilt:hilt-navigation-compose:1.2.0")

// retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'

// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.7.0'

// status bar color
implementation("com.google.accompanist:accompanist-systemuicontroller:0.31.5-beta")

// date picker
implementation 'com.squaredem:composecalendar:1.0.0'

implementation("androidx.constraintlayout:constraintlayout:2.2.0-alpha13")

// To use constraintlayout in compose
implementation("androidx.constraintlayout:constraintlayout-compose:1.1.0-alpha13")

implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0")

// room
def room_version = "2.6.1"
implementation("androidx.room:room-runtime:$room_version")
testImplementation("androidx.room:room-testing:$room_version")
ksp("androidx.room:room-compiler:$room_version")
implementation("androidx.room:room-ktx:$room_version")

// material theme
implementation "androidx.compose.material:material-icons-extended:1.6.7"
implementation("androidx.compose.material3:material3:1.2.1")
implementation("androidx.datastore:datastore-preferences:1.1.1")

// optional - RxJava2 support
implementation("androidx.datastore:datastore-preferences-rxjava2:1.1.1")

// optional - RxJava3 support
implementation("androidx.datastore:datastore-preferences-rxjava3:1.1.1")

def compose_version = "1.5.3"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation "androidx.room:room-testing:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
testImplementation "org.mockito:mockito-core:4.8.0"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
testImplementation "org.mockito.kotlin:mockito-kotlin:4.1.0"
androidTestImplementation "org.mockito.kotlin:mockito-kotlin:4.1.0"
androidTestImplementation "org.mockito:mockito-android:4.8.0"
androidTestImplementation "androidx.test:core:1.5.0"
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version"
androidTestImplementation "androidx.navigation:navigation-testing:2.8.3"
debugImplementation("androidx.compose.ui:ui-test-manifest:$compose_version")

implementation "androidx.compose.material3:material3:1.2.0"

implementation 'androidx.core:core-splashscreen:1.0.1'

}

is there anything wrong in my dependencies ? Any compatibility issues with Kotlin version?



Подробнее здесь: https://stackoverflow.com/questions/794 ... use-of-thi
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»