Espresso error stubbing camera intent , Wanted to match 1 intents. Actually matched 0 intents

199
December 20, 2019, at 4:50 PM

I'm attempting to stub camera intent in Espresso UI testing and getting an error as mentioned bellow

      ----- begin exception -----
E/TestRunner: androidx.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: Wanted to match 1 intents. Actually matched 0 intents.
    IntentMatcher: has data: is <android.resource://com.example.espressopracticetests/drawable/ic_launcher_background>
    Matched intents:[]
    Recorded intents:
    -Intent { act=android.media.action.IMAGE_CAPTURE (has extras) } handling packages:[[com.android.camera2]], extras:[Bundle[{output=content://media/external/images/media/42}]])
        at dalvik.system.VMStack.getThreadStackTrace(Native Method)
        at java.lang.Thread.getStackTrace(Thread.java:1720)
        at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:96)
        at androidx.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:59)
        at androidx.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:324)
        at androidx.test.espresso.ViewInteraction.check(ViewInteraction.java:306)
        at androidx.test.espresso.intent.Intents.intended(Intents.java:190)
        at androidx.test.espresso.intent.Intents.intended(Intents.java:170)
        at com.example.espressopracticetests.IntentsAdvancedSample.CameraTaskTest.takePhoto_drawableIsApplied(CameraTaskTest.kt:97)
        at java.lang.reflect.Method.invoke(Native Method)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
        at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
        at androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
        at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
        at androidx.test.rule.GrantPermissionRule$RequestPermissionStatement.evaluate(GrantPermissionRule.java:134)
        at org.junit.rules.RunRules.evaluate(RunRules.java:20)
        at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at androidx.test.ext.junit.runners.AndroidJUnit4.run(AndroidJUnit4.java:104)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:395)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2189)
     Caused by: junit.framework.AssertionFailedError: Wanted to match 1 intents. Actually matched 0 intents.
    IntentMatcher: has data: is <android.resource://com.example.espressopracticetests/drawable/ic_launcher_background>
    Matched intents:[]
    Recorded intents:
    -Intent { act=android.media.action.IMAGE_CAPTURE (has extras) } handling packages:[[com.android.camera2]], extras:[Bundle[{output=content://media/external/images/media/42}]])
        at junit.framework.Assert.fail(Assert.java:50)
        at androidx.test.espresso
    ----- end exception -----    

The code in Kotlin for capturing image with camera is as follows

class CameraTask : AppCompatActivity() {
    private val PERMISSION_CODE = 1000;
    private val IMAGE_CAPTURE_CODE = 1001
    var image_uri: Uri? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_task)
        //button click
        button_take_photo.setOnClickListener {
            //if system os is Marshmallow or Above, we need to request runtime permission
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                if (checkSelfPermission(Manifest.permission.CAMERA)
                    == PackageManager.PERMISSION_DENIED ||
                    checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_DENIED){
                    //permission was not enabled
                    val permission = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    //show popup to request permission
                    requestPermissions(permission, PERMISSION_CODE)
                }
                else{
                    //permission already granted
                    openCamera()
                }
            }
            else{
                //system os is < marshmallow
                openCamera()
            }
        }
    }
    private fun openCamera() {
        val values = ContentValues()
        values.put(MediaStore.Images.Media.TITLE, "New Picture")
        values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera")
        image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
        //camera intent
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
        startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        //called when user presses ALLOW or DENY from Permission Request Popup
        when(requestCode){
            PERMISSION_CODE -> {
                if (grantResults.size > 0 && grantResults[0] ==
                    PackageManager.PERMISSION_GRANTED){
                    //permission from popup was granted
                    openCamera()
                }
                else{
                    //permission from popup was denied
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode,resultCode,data)
        //called when image was captured from camera intent
        if (resultCode == Activity.RESULT_OK){
            //set image captured to image view
            imageView.setImageURI(image_uri)
        }
    }
}

The Espresso UI testing code is as follows

package com.example.espressopracticetests.IntentsAdvancedSample
import android.app.Activity
import android.app.Instrumentation.ActivityResult
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.core.internal.deps.guava.collect.Iterables
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers
import androidx.test.espresso.intent.matcher.IntentMatchers.*
import androidx.test.espresso.intent.rule.IntentsTestRule
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.test.rule.GrantPermissionRule
import com.example.espressopracticetests.IntentsAdvancedSample.ImageViewHasDrawableMatcher.hasDrawable
import com.example.espressopracticetests.R
import org.hamcrest.core.AllOf.allOf
import org.hamcrest.core.IsNot.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
@LargeTest
class CameraTaskTest {
    /*@Rule are interceptors that which are executed before any of your setup code and are executed for each test*/
    @get:Rule
    var grantPermissionRule = GrantPermissionRule.grant(
        "android.permission.CAMERA",
        "android.permission.WRITE_EXTERNAL_STORAGE"
    )
    /*A rule to init and release Espresso Intents before and after each
     * test run.*/
    @get:Rule
    val intentsTestRule = IntentsTestRule(CameraTask::class.java)
    lateinit var context: Context
    lateinit var stubUri: Uri

    @Before
    fun stubCameraIntent() {
        context = ApplicationProvider.getApplicationContext<Context>()
        stubUri =
            Uri.parse("android.resource://com.example.espressopracticetests/drawable/ic_launcher_background")
        val result = createImageCaptureActivityResultStub()
        // Stub the Intent.
        Intents.intending(IntentMatchers.hasAction(MediaStore.ACTION_IMAGE_CAPTURE))
            .respondWith(result)
    }
    @Test
    fun takePhoto_drawableIsApplied() { // Check that the ImageView doesn't have a drawable applied.
        // Check that the ImageView doesn't have a drawable applied.
        onView(withId(R.id.imageView)).check(matches(not(hasDrawable())))
        // Click on the button that will trigger the stubbed intent.
        onView(withId(R.id.button_take_photo)).perform(ViewActions.click())
        onView(
            allOf(
                withId(R.id.imageView),
                hasBackground(R.drawable.ic_launcher_background), isDisplayed()
            )
        )
        val receivedIntent =
            Iterables.getOnlyElement(
                Intents.getIntents()
            )
        intended(toPackage("com.android.camera2"));
        val uri = receivedIntent.extras
        val action = receivedIntent.action
        System.out.println(action)
        intended(hasData("android.resource://com.example.espressopracticetests/drawable/ic_launcher_background"))
        intended(hasAction(MediaStore.ACTION_IMAGE_CAPTURE))
        System.out.println(uri.toString())
    }
    // Creating a dummy ActivityResult with data
    fun createImageCaptureActivityResultStub(): ActivityResult {
        val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        System.out.println(stubUri.toString())
        // Create the Intent that will include the bundle.
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, stubUri)
        // Create the ActivityResult with the Intent.
        return ActivityResult(Activity.RESULT_OK, cameraIntent)
    }
}

I'm failing to understand how I can get this fixed and need some deep insights on how it can be resolved.

Rent Charter Buses Company
READ ALSO
FTPS can&#39;t connect on android devices with self singed certificate

FTPS can't connect on android devices with self singed certificate

I have FTP server on Raspberry PI with RaspbianI use vsftpd, port 990 and GreenLock cetificate

92
How to check if dark theme exists in Android OS?

How to check if dark theme exists in Android OS?

Officially dark theme is available in Android 10, but in reality, dark theme available in Android 9 MIUI 11 for exampleIs there a way to check programmatically if OS dark theme available or not? I tried to check it through the Configuration#uiMode field:

128
What are the pros and cons of storing image in database as URI or as byte array? [closed]

What are the pros and cons of storing image in database as URI or as byte array? [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post

85
How to make sure an Input Integer stays an Integer on Form Submit

How to make sure an Input Integer stays an Integer on Form Submit

I am trying to integrate a payment gateway to my websiteWhat I need to do is to send:

123