简体   繁体   中英

R.id not found when writing Espresso test

I tried writing a small test to try Espresso.

package com.mycompany.myapp.somemodule

import com.mycompany.myapp.R
import other.uselful.imports

@RunWith(AndroidJUnit4::class)
@LargeTest
class DemoTest {

    @get:Rule
    var startActivity: ActivityTestRule<StartActivity> = ActivityTestRule(StartActivity::class.java)


    @Test
    fun aDemoTest() {
        onView(withId(R.id.theElementId))
                .check(matches(isClickable()))
    }
}

Android Studio doesn't show any error. if I ctrl+click on R.id.theElementID , it finds it in the appropriate layout file. However when I try to run, I get a compile error:

Unresolved reference: id

How can I solve this?

I bumped into this issue. Spent 4 hours investigating, and no luck finding anything useful on the internet.

So, I'm hoping that the information below may help someone.

Short answer:

  1. clean the project
  2. execute gradlew :app:build from the command line / Terminal, it may show a build error which leads to the root cause

The longer answer:

I did the following:

  1. I hit "Invalidate caches and restart" from Android Studio
  2. I've executed gradlew :app:build from the command line

The second step printed an error message that the BuildConfig was duplicated. The reason for this issue was, that I had 2 modules (android-app and android-library) with slightly different package names (I made a typo when creating the second one). This led to the failed build from the command line. After modifying the 2nd module's package name to be the same as the 1st one, the issue was solved.

I didn't receive the "R.id not found" error. So, I could continue to write the UI tests, which worked :-)

Happy coding!

guess the actual problem is, that the activity had not been started.

R.id.theElementId might be an invalid resource descriptor.

try R.id.the_element_id instead.

also, add @UiThreadTest annotation ...

Short answer: Try remove any incorrect import android.R statement.

Long answer I also have faced this issue.

In my case, in test class, I was importing android.R package due to referring some incorrect resource id previously ( R.id.progress ) which belonged to android.R package.

I removed that reference as well ans the import statement ie import android.R from the test class and the issue resolved. Then source recognized the R.id.etPassword resource id of my layout file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM