Android - Testing Fragments With Espresso by Using launchFragmentInContainer Never Completes - android

My test is never running to completion and I have absolutely no idea why. I can see the toast displayed on my phone's screen. There is absolutely nothing in the logs.
#RunWith(AndroidJUnit4::class)
#SmallTest
class BaseDataFragmentUITest
{
#Test
fun isDisplayingToastWhenFAILED_TO_UPDATE()
{
val fragmentScenario = launchFragmentInContainer<TestBaseDataFragmentImp>()
val toastString: String = context.resources.getString(com.developerkurt.gamedatabase.R.string.data_update_fail)
fragmentScenario.onFragment {
it.handleDataStateChange(BaseRepository.DataState.FAILED_TO_UPDATE)
onView(withText(toastString)).inRoot(withDecorView(not(it.requireActivity().getWindow().getDecorView()))).check(matches(isDisplayed()))
}
}
}

Apparently, Espresso assertions shouldn't be made inside of the onFragment block. So when I wrote the test like this it worked:
#Test
fun isDisplayingToastWhenFAILED_TO_UPDATE()
{
val fragmentScenario = launchFragmentInContainer<TestBaseDataFragmentImp>()
val toastString: String = context.resources.getString(com.developerkurt.gamedatabase.R.string.data_update_fail)
var decorView: View? = null
fragmentScenario.onFragment {
it.handleDataStateChange(BaseRepository.DataState.FAILED_TO_UPDATE)
decorView = it.requireActivity().getWindow().getDecorView()
}
onView(withText(toastString)).inRoot(withDecorView(not(decorView!!))).check(matches(isDisplayed()))
}

Related

changing test cases from junit to mockito in android app

i am trying to test out an email field in login screen. i want to change the following code using mockito. can it be done. pls help??
class EmailValidatorTest {
#Test
fun emailValidator_CorrectEmailSimple_ReturnsGood() {
val email = "name#email.com"
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.GOOD)
}
#Test
fun emailValidator_CorrectEmailSubDomain_ReturnsGood() {
val email = "name#email.co.uk"
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.GOOD)
}
#Test
fun emailValidator_InvalidEmailNoTld_ReturnsIncorrect() {
val email = "name#email"
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.INCORRECT)
}
#Test
fun emailValidator_InvalidEmailDoubleDot_ReturnsIncorrect() {
val email = "name#email..com"
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.INCORRECT)
}
#Test
fun emailValidator_InvalidEmailNoUsername_ReturnsIncorrect() {
val email = "#email.com"
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.INCORRECT)
}
#Test
fun emailValidator_EmptyString_ReturnsEmpty() {
val email = ""
assertThat(EmailPasswordChecker.getEmailState(email)).isEqualTo(EmailState.EMPTY)
}
here is some more helper code->
object EmailPasswordChecker{
//some code that i cant share
}
enum class EmailState {
GOOD,
INCORRECT,
EMPTY
}
these are simple tests that i wrote using JUnit. but now i need to change them using mockito. can someone help me with the code? i am fairly new to testing so i am not exactly able to figure out how this framework is working.

How to assert next started activity for a composable test?

I have a composable with a button that launches one of the native activities (Google Settings).
To test this before compose (using Robolectric) I would do something like this:
My test:
#Test
fun `MyFragment - when button clicked - starts activity`() {
// ...
val shadowActivity: ShadowActivity = Shadow.extract(activity)
val nextStartedActivity = shadowActivity.nextStartedActivity
assertNotNull(nextStartedActivity)
assertEquals(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, nextStartedActivity.action)
}
With compose tests (not using activity scenario) it's different. There is no activity handle, only a composeTestRule:
My test:
// ...
private val buttonNode get() = composeTestRule.onNodeWithContentDescription("Button")
#Test
fun `MyComposableToTest - when button clicked - starts activity`() {
composeTestRule.setContent {
MyComposableToTest()
}
buttonNode.assertExists().assertHasClickAction().assertIsEnabled().performClick()
// No possibility to get current activity
}
How can I assert that a new activity is started when testing a Composable?
Some context:
Android Gradle Plugin 7.0.3
Robolectric 4.7.3
Compose 1.1.0-beta04
You are able to fetch the context from the ComposeContentTestRule like this:
lateinit var context : Context
composeTestRule.setContent {
context = LocalContext.current
MyComposableToTest()
}
and then to assert the next started activity
val shadowActivity: ShadowActivity = Shadow.extract(context as ComponentActivity)
val nextStartedActivity = shadowActivity.nextStartedActivity
assertEquals(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, nextStartedActivity.action)
This is how I did it for my instrumented test (NOT using Robolectric).
build.gradle[.kts]:
androidTestImplementation("androidx.test.espresso:espresso-intents:3.4.0")
The test class (in src/androidTest/... directory):
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
// ...
#RunWith(AndroidJUnit4::class)
class MainActivityInstrumentedTest {
#get:Rule val composeTestRule = createAndroidComposeRule<MainActivity>()
#Test fun testTheIntent() {
Intents.init() // IMPORTANT (to be able to use "intended" function)
composeTestRule.setContent {
MyAppTheme {
MainScreen()
}
}
composeTestRule.onNodeWithText("My Button").performClick()
intended(hasComponent(MySecondActivity::class.java.name))
Intents.release()
}
}

Waiting for livedata to complete in UI Espresso test

I'm new to testing and Espresso, so bear with me please.
I have an app with some simple image editing and I have decided to cover it with UI tests.
For starters I have decided to test the initial image uploading, processing and moving to the next screen.
here is the test I came up with so far:
#LargeTest
#RunWith(AndroidJUnit4::class)
class VerifyLoadImage {
lateinit var testContext: Context
#Rule
#JvmField
var mActivityTestRule = ActivityScenarioRule(MainActivity::class.java)
#Before
fun loadContext() {
testContext = InstrumentationRegistry.getInstrumentation().context
}
#Test
fun loadImageToCrop() {
mActivityTestRule.scenario.onActivity { mainActivity ->
// get the activity
val navigationFragment = mainActivity.supportFragmentManager.findFragmentById(R.id.fragmentContainer)
//verify that current fragment displayed is ImagePickerFragment
val currentFragment = navigationFragment?.getDisplayedChildFragment()?.let { it as? ImagePickerFragment }
?: throw AssertionError("currentFragment is not instance of ImagePickerFragment")
//call the method to upload the image from input stream, process it and then navigate to the crop screen
currentFragment.loadBitmapAndOpenCropScreen(AssetInputStreamProvider(testContext, "sample_image.jpg"))
//verify that crop screen is currently displayed
assert(navigationFragment.getDisplayedChildFragment() is CropFragment)
}
}
}
private fun Fragment.getDisplayedChildFragment() = childFragmentManager.fragments.first()
this is the code in currentFragment.loadBitmapAndOpenCropScreen
internal fun loadBitmapAndOpenCropScreen(inputStreamProvider: InputStreamProvider) {
activityViewModel.loadBitmap(inputStreamProvider).observe(viewLifecycleOwner) {
when (it) {
Loading -> showLoading()
is Success -> {
hideLoading()
findNavController().navigate(ImagePickerFragmentDirections.toCrop())
}
is Error -> hideLoading()
}
}
}
the problem is that when testing, the LiveData never changes updates at all [works normally when launching the app].
I would appreciate any help here.
Try InstantTaskExecutorRule
#Rule
#JvmField
var mInstantTaskExecutorRule = InstantTaskExecutorRule()

Unit testing coroutines runBlockingTest: This job has not completed yet

Please find below a function using a coroutine to replace callback :
override suspend fun signUp(authentication: Authentication): AuthenticationError {
return suspendCancellableCoroutine {
auth.createUserWithEmailAndPassword(authentication.email, authentication.password)
.addOnCompleteListener(activityLifeCycleService.getActivity()) { task ->
if (task.isSuccessful) {
it.resume(AuthenticationError.SignUpSuccess)
} else {
Log.w(this.javaClass.name, "createUserWithEmail:failure", task.exception)
it.resume(AuthenticationError.SignUpFail)
}
}
}
}
Now I would like to unit testing this function. I am using Mockk :
#Test
fun `signup() must be delegated to createUserWithEmailAndPassword()`() = runBlockingTest {
val listener = slot<OnCompleteListener<AuthResult>>()
val authentication = mockk<Authentication> {
every { email } returns "email"
every { password } returns "pswd"
}
val task = mockk<Task<AuthResult>> {
every { isSuccessful } returns true
}
every { auth.createUserWithEmailAndPassword("email", "pswd") } returns
mockk {
every { addOnCompleteListener(activity, capture(listener)) } returns mockk()
}
service.signUp(authentication)
listener.captured.onComplete(task)
}
Unfortunately this test failed due to the following exception : java.lang.IllegalStateException: This job has not completed yet
I tried to replace runBlockingTest with runBlocking but the test seems to wait in an infinite loop.
Can someone help me with this UT please?
Thanks in advance
As can be seen in this post:
This exception usually means that some coroutines from your tests were scheduled outside the test scope (more specifically the test dispatcher).
Instead of performing this:
private val networkContext: CoroutineContext = TestCoroutineDispatcher()
private val sut = Foo(
networkContext,
someInteractor
)
fun `some test`() = runBlockingTest() {
// given
...
// when
sut.foo()
// then
...
}
Create a test scope passing test dispatcher:
private val testDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testDispatcher)
private val networkContext: CoroutineContext = testDispatcher
private val sut = Foo(
networkContext,
someInteractor
)
Then in test perform testScope.runBlockingTest
fun `some test`() = testScope.runBlockingTest {
...
}
See also Craig Russell's "Unit Testing Coroutine Suspend Functions using TestCoroutineDispatcher"
In case of Flow testing:
Don't use flow.collect directly inside runBlockingTest. It should be wrapped in launch
Don't forget to cancel TestCoroutineScope in the end of a test. It will stop a Flow collecting.
Example:
class CoroutinesPlayground {
private val job = Job()
private val testDispatcher = StandardTestDispatcher()
private val testScope = TestScope(job + testDispatcher)
#Test
fun `play with coroutines here`() = testScope.runBlockingTest {
val flow = MutableSharedFlow<Int>()
launch {
flow.collect { value ->
println("Value: $value")
}
}
launch {
repeat(10) { value ->
flow.emit(value)
delay(1000)
}
job.cancel()
}
}
}
This is not an official solution, so use it at your own risk.
This is similar to what #azizbekian posted, but instead of calling runBlocking, you call launch.
As this is using TestCoroutineDispatcher, any tasks scheduled to be run without delay are immediately executed. This might not be suitable if you have several tasks running asynchronously.
It might not be suitable for every case but I hope that it helps for simple cases.
You can also follow up on this issue here:
https://github.com/Kotlin/kotlinx.coroutines/issues/1204
If you know how to solve this using the already existing runBlockingTest and runBlocking, please be so kind and share with the community.
class MyTest {
private val dispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(dispatcher)
#Test
fun myTest {
val apiService = mockk<ApiService>()
val repository = MyRepository(apiService)
testScope.launch {
repository.someSuspendedFunction()
}
verify { apiService.expectedFunctionToBeCalled() }
}
}
According to my understanding, this exception occurs when you are using a different dispatcher in your code inside the runBlockingTest { } block with the one that started runBlockingTest { }.
So in order to avoid this, you first have to make sure you inject Dispatchers in your code, instead of hardcoding it throughout your app. If you haven't done it, there's nowhere to begin because you cannot assign a test dispatcher to your test codes.
Then, in your BaseUnitTest, you should have something like this:
#get:Rule
val coroutineRule = CoroutineTestRule()
#ExperimentalCoroutinesApi
class CoroutineTestRule(
val testDispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()
) : TestWatcher() {
override fun finished(description: Description?) {
super.finished(description)
Dispatchers.setMain(testDispatcher)
}
override fun starting(description: Description?) {
super.starting(description)
Dispatchers.resetMain()
testDispatcher.cleanupTestCoroutines()
}
}
Next step really depends on how you do Depedency Injection. The main point is to make sure your test codes are using coroutineRule.testDispatcher after the injection.
Finally, call runBlockingTest { } from this testDispatcher:
#Test
fun `This should pass`() = coroutineRule.testDispatcher.runBlockingTest {
//Your test code where dispatcher is injected
}
There is an open issue for this problem: https://github.com/Kotlin/kotlinx.coroutines/issues/1204
The solution is to use the CoroutineScope intead of the TestCoroutinScope until the issue is resolved, you can do by replacing
#Test
fun `signup() must be delegated to createUserWithEmailAndPassword()`() =
runBlockingTest {
with
#Test
fun `signup() must be delegated to createUserWithEmailAndPassword()`() =
runBlocking {
None of these answers quite worked for my setup due to frequent changes in the coroutines API.
This specifically works using version 1.6.0 of kotlin-coroutines-test, added as a testImplementation dependency.
#Test
fun `test my function causes flow emission`() = runTest {
// calling this function will result in my flow emitting a value
viewModel.myPublicFunction("1234")
val job = launch {
// Force my flow to update via collect invocation
viewModel.myMemberFlow.collect()
}
// immediately cancel job
job.cancel()
assertEquals("1234", viewModel.myMemberFlow.value)
}
If you have any
Channel
inside the launch, you must call to
Channel.close()
Example code:
val channel = Channel<Success<Any>>()
val flow = channel.consumeAsFlow()
launch {
channel.send(Success(Any()))
channel.close()
}
runBlockingTest deprecated since 1.6.0 and replaced with runTest.
You need to swap arch background executor with one that execute tasks synchronously. eg. For room suspend functions, live data etc.
You need the following dependency for core testing
androidTestImplementation 'androidx.arch.core:core-testing:2.1.0'
Then add the following at the top of test class
#get:Rule
val instantExecutor = InstantTaskExecutorRule()
Explanations
InstantTaskExecutorRule A JUnit Test Rule that swaps the background executor used by the
Architecture Components with a different one which executes each task
synchronously.
You can use this rule for your host side tests that use Architecture
Components
As I mentioned here about fixing runBlockingTest, maybe it could help you too.
Add this dependency if you don't have it
testImplementation "androidx.arch.core:core-testing:$versions.testCoreTesting" (2.1.0)
Then in your test class declare InstantTaskExecutorRule rule:
#get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()

Android Instrumented testing asserting if an activity is started

I am developing an Android application using Kotlin programming language. I am adding instrumentation tests into my application. Now I am trying to test if an activity is started after some delay.
This is my activity code.
class MainActivity : AppCompatActivity() {
companion object {
val LAUNCH_DELAY: Long = 2000
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
Handler().postDelayed({
this.startLoginActivity()
}, LAUNCH_DELAY)
}
protected fun startLoginActivity()
{
startActivity(Intent(this, LoginActivity::class.java))
}
}
I know how to write a simple test like this
#Test
fun itRendersCompanyName() {
onView(withId(R.id.main_tv_company_name)).check(matches(withText("App Name")))
}
But what I am trying to test here is if the LoginActivity is launched after some delay. How can I do it using Espresso framework?
You can get the visible Activity using ActivityManager:
inline fun <reified T : Activity> isVisible(): Boolean {
val am = ApplicationProvider.getApplicationContext<Context>().getSystemService(ACTIVITY_SERVICE)
as ActivityManager
val visibleActivityName = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
am.appTasks[0].taskInfo.topActivity.className
} else {
am.getRunningTasks(1)[0].topActivity.className
}
return visibleActivityName == T::class.java.name
}
Calling isVisible<LoginActivity>() will tell you that LoginActivity is visible or not.
Also, to wait until your LoginActivity visible, you can wait for this method to gets true. For example:
inline fun <reified T : Activity> waitUntilActivityVisible() {
val startTime = System.currentTimeMillis()
while (!isVisible<T>()) {
Thread.sleep(200)
if (System.currentTimeMillis() - startTime >= TIMEOUT) {
throw AssertionError("Condition unsatisfied after $TIMEOUT milliseconds")
}
}
}
You can use Intents.intended() for that.
Add following to your build.gradle file:
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'
In your test function, you can try following code:
Intents.init()
Intents.intended(hasComponent(LoginActivity::class.java!!.getName()))
You can read more about Espresso-Intents here.
It’s better to test this state with unit tests. Use architecture pattern (for example MVP/MVVM), mock presenter/view model and check what method which is responsible for activity start is triggered
I got it working using the following:
val expectedUrl = "https://yoururlhere"
Intents.init();
Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(expectedUrl));
intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
onView(withId(R.id.someViewId)).perform(click());
intended(expectedIntent);
Intents.release();
And remember to add "androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'" to your gradle dependency

Categories

Resources