GrantPermissionRule未解决的参考

时间:2019-03-21 17:16:02

标签: android kotlin

我正在使用Android Studio通过kotlin创建一个应用。我正在尝试对MainActivity类进行单元测试,并且由于我使用的是API 28,因此需要授予权限才能运行单元测试。我在测试类的顶部放了@get:Rule varPermissionRule = GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO),但是Android Studio告诉我GrantPermissionRule是一个未解决的参考。我的代码在下面。

MainActivity类:

class MainActivity : AppCompatActivity(), MediaPlayer.OnCompletionListener {

    lateinit var recorder: MediaRecorder
    lateinit var player: MediaPlayer
    lateinit var file: File
    lateinit var button1: Button
    lateinit var button2: Button
    lateinit var button3: Button
    lateinit var tv1: TextView
    // coding180.com

    override fun onCreate(savedInstanceState: Bundle?) {

        // call the super class onCreate to complete the creation of activity 
        // like the view hierarchy
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getPermissionToRecordAudio()
        }

        tv1 = findViewById(R.id.tv1) as TextView
        button1 = findViewById(R.id.btnStart) as Button
        button2 = findViewById(R.id.btnStop) as Button
        button3 = findViewById(R.id.btnPlay) as Button

        ...

    }

测试类:

@RunWith(RobolectricTestRunner::class)
class MainActivityTest {

    @get:Rule var permissionRule = 
             GrantPermissionRule.grant(android.Manifest.permission.RECORD_AUDIO)

    lateinit var testMainActivity: MainActivity

    @Before
    fun setup() {
        testMainActivity = MainActivity()
    }

    @Test
    @Throws(Exception::class)
    fun onCreateTest() {

        //Activity variables
        val intent = Intent()
        val bundle = Bundle()
        intent.putExtras(bundle)
        val controller = Robolectric.buildActivity(MainActivity::class.java, 
                                                   intent).create()
        val activity = controller.get() as Activity

        //Start activity
        controller.start()

        //Asserts
        assertFalse(activity.isFinishing)
    }

我找不到其他遇到此问题的人。有谁知道为什么Android Studio无法识别GrantPermissionRule以及如何解决?

1 个答案:

答案 0 :(得分:1)

您的代码看起来不错,添加

androidTestImplementation 'com.android.support.test:rules:1.0.2'

致您的build.gradle