ActivityScenario.launch forced finish - android

import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
#RunWith(AndroidJUnit4::class)
class MainActivityTest {
#Test
fun setupData() {
var activityScenario = ActivityScenario.launch(MainActivity::class.java)
activityScenario.onActivity {
}
}
}
I don't know why it forces finish() is called.
I override finish method, but it called twice and force closing.

Related

mockito is not working for sharedPreferences with instrumentedTest

I have three activity activityA, activityB and activityC.
whenever we will start app it will launch activityA and based on shared preferences (based on boolean value which we will receive from shared preferences.) it will start activityB or activityC with onCreate Activity lifecycle event
here is my test code
package com.panther_nine.t2_mini
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.*
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import com.panther_nine.t2_mini.database.sharedPref.dao.AppDao
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
#LargeTest
#RunWith(AndroidJUnit4::class)
class ActivityATest {
#Mock
private lateinit var mPreferences: SharedPreferences
#Mock
private lateinit var mContext: Context
#get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java, true, false)
#Before
fun setup(){
MockitoAnnotations.initMocks(this)
`when`(mContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mPreferences)
}
#Test
fun testEvent() {
`when`(mPreferences.getBoolean(anyString(), anyBoolean())).thenReturn(false)
activityRule.launchActivity(Intent())
}
}
whenever I am launching my code sharedPreferences always returnning "true". it mean that mocking is not working

testing Repository class that takes DAO parameter

I am learning Kotlin to build a note app. I have created a repository class as shown below which takes a Dao parameter. For now, the source of data is just Dao but in the tutorial I am following, it calls an API class as well.
What I want to know is how do I test a repository classes logic?
import androidx.lifecycle.LiveData
import com.example.lastnotetakingapp.db.daos.NoteDao
import com.example.lastnotetakingapp.db.models.Note
class NotesRepo(private val notesDao: NoteDao) {
val allNotes: LiveData<List<Note>> = notesDao.getAllNotes()
suspend fun addNewNote(note: Note): Long {
return notesDao.addNewNote(note)
}
}
My test which is passing but it is 100% identical to the way a Dao would be tested except I use repo object, which made wonder if I am doing it right or not:
Is mocking the Database/DAO possible so I can spy on them to make sure they are called and all?
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.lastnotetakingapp.db.NoteDB
import com.example.lastnotetakingapp.db.daos.NoteDao
import com.example.lastnotetakingapp.db.models.Note
import com.example.lastnotetakingapp.testHelpers.getOrAwaitValue
import com.google.common.truth.Truth
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
#RunWith(AndroidJUnit4::class)
class NotesRepoTest {
private lateinit var dao: NoteDao
private lateinit var db: NoteDB
private lateinit var notesRepo: NotesRepo
#get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
#Before
fun setUp(){
db = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
NoteDB::class.java,
).allowMainThreadQueries().build()
dao= db.noteDao
notesRepo = NotesRepo(dao)
}
#After
fun tearDown(){
db.close()
}
#Test
fun saveNotesTest(): Unit = runBlocking{
val note = Note(0, "tupac", "content", 0)
val id : Long = notesRepo.addNewNote(note)
Truth.assertThat(id).isEqualTo(1)
val notes = notesRepo.allNotes.getOrAwaitValue()
val noteOne: Note? = notes?.get(0)
Truth.assertThat(notes?.size).isEqualTo(1)
Truth.assertThat(noteOne?.title).isEqualTo(note.title)
Truth.assertThat(noteOne?.content).isEqualTo(note.content)
Truth.assertThat(noteOne?.viewed).isEqualTo(false)
}
}

Some Junit5 test codes are not run

I am developing an android with Junit5 and Mockito.
Some tests are ParameterizedTest and others are just Test.
Here is my sample code.
When I run this test, only "ParameterizedTests" run.
"JustTests" is not shown on the JUnit test console list.
How can I run "JustTests" too?
import org.junit.Test
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import org.mockito.InOrder
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.*
import org.mockito.MockitoAnnotations
internal class MyPresenterTest {
#Mock
private lateinit var view: MyContract.View
private lateinit var presenter: MyContract.Presenter
#BeforeEach
fun setup() {
MockitoAnnotations.openMocks(this)
presenter = MyPresenter(view)
}
#Nested
#DisplayName("Just Test")
inner class JustTests {
#DisplayName("test 1")
#Test
fun greetingTest1() {
...
}
}
#Nested
#DisplayName("Parameterized test")
inner class ParameterizedTests {
#ParameterizedTest(name = "{0}")
#ValueSource(strings = ["Hello", "Hi])
#Test
fun greetingTest2(greeting: String) {
...
}
}
}

Why does my Android Unit Test runs twice?

Here is the complete test class for my Kotlin unit tests:
package xyz.hitit.userapplication.unittests.fragmentUnitTests
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import org.junit.After
import org.junit.Before
import org.junit.Test
import xyz.hitit.userapplication.ui.registrationLogin.VerificationCodeFragment
class VerificationCodeFragmentUnitTests {
var scenario: FragmentScenario<VerificationCodeFragment>? = null
#Before
fun setup() {
scenario = launchFragmentInContainer<VerificationCodeFragment>()
}
#Test
fun testHandleVerificationCodeResult2() {
scenario?.onFragment { sut ->
sut.didRun = false
var menu = "NotAnEmailSearch"
sut.handleVerificationCodeResult(menu = menu, userInputVerCode = "list2")
assert(sut.didRun == true)
}
}
#After
fun tearDown() {
scenario = null
}
}
Whenever I run this test class testHandleVerificationCodeResult2() runs twice and the last one fails. Which process should I take to find the solution??

Lifecycle.addObserverUntilDestroy extension stopped working with AndroidX

I've been using following Kotlin extension to add my lifecycle observers:
fun Lifecycle.addObserverUntilDestroy(observer: LifecycleObserver) {
addObserver(observer)
addObserver(object : LifecycleObserver {
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun onDestroy() {
removeObserver(this)
removeObserver(observer)
}
})
}
The idea was to automatically remove the observer when the Lifecycle is being destroyed.
So I can call it in Activity's onPostCreate (in this case a Java code but it is the same when calling from Kotlin):
ArchitectureComponentExtensions.addObserverUntilDestroy(getLifecycle(), myViewModel);
And have this code in my ViewModel (a custom one, not the on from Architecture Components):
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onViewDestroyed() {
// This is not being called anymore
}
But this stopped working after migrating from:
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleObserver
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.OnLifecycleEvent
to:
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
Any ideas why this is not working anymore?

Categories

Resources