Нужна помощь с тестированием моего приложения. Я хочу проверить viewmodel fun writeNewTask () . Он должен добавить Task объект в базу данных под родителями под названием tasks и персональный id каждой задачи.
fun writeNewTask(name: String?, orphanage: String?) {
val id = database.push().key!!
val task = Task(id, name, orphanage)
database.child("tasks").child(id).setValue(task)
}
I'm используя PowerMock. Вот так выглядит мой тест
@RunWith(PowerMockRunner::class)
@PowerMockRunnerDelegate(JUnit4::class)
@PrepareForTest(FirebaseDatabase::class, AddTaskViewModel::class, DatabaseReference::class)
@PowerMockIgnore("org.mockito.*", "org.robolectric.*", "android.*", "androidx.*")
class AddTaskViewModelTest {
@Mock
lateinit var mockedDatabase: FirebaseDatabase
@Mock
lateinit var databaseReference: DatabaseReference
@Mock
lateinit var viewModel: AddTaskViewModel
@Before
fun before() {
viewModel = PowerMockito.mock(AddTaskViewModel::class.java)
databaseReference = PowerMockito.mock(DatabaseReference::class.java)
PowerMockito.mockStatic(AddTaskViewModel::class.java)
PowerMockito.mockStatic(DatabaseReference::class.java)
PowerMockito.mockStatic(FirebaseDatabase::class.java)
`when`(FirebaseDatabase.getInstance()).thenReturn(mockedDatabase)
mockedDatabase = PowerMockito.mock(FirebaseDatabase::class.java)
`when`(mockedDatabase.reference).thenReturn(databaseReference)
}
@Test
fun writeNewTaskTest() {
val id = "1"
`when`(databaseReference.key).thenReturn(id)
val name = "name"
val orphanage = "orphanage"
val task = Task(id, name, orphanage)
viewModel.writeNewTask(name, orphanage)
verify(databaseReference)
.child("tasks")
.child(id)
.setValue(task)
}
}
И я улавливаю эту ошибку. После отладки я выяснил, что child ("задачи") равен null
databaseReference.child("tasks");
-> at com.example.application.viewModel.AddTaskViewModelTest.writeNewTaskTest(AddTaskViewModelTest.kt:59)
Actually, there were zero interactions with this mock.
Wanted but not invoked:
databaseReference.child("tasks");
-> at com.example.application.viewModel.AddTaskViewModelTest.writeNewTaskTest(AddTaskViewModelTest.kt:59)
Actually, there were zero interactions with this mock.