Espresso错误存根相机意图,想要匹配1个意图。实际匹配的0个意图

时间:2019-12-19 11:32:08

标签: android kotlin android-espresso androidx android-instrumentation

我正在尝试在Espresso UI测试中存根摄像机意图,并出现如下所述的错误

      ----- 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 -----    

Kotlin中使用相机捕获图像的代码如下

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)
        }
    }

}


Espresso UI测试代码如下

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)

    }

}

我无法理解如何解决此问题,需要深入了解如何解决它。

0 个答案:

没有答案