kotlinjunit4android-espressookhttpmockwebserver

An annotation argument must be a compile-time constant @RunWith(AndroidJUnit4::class)


My test suite won't run and it appears to be the @RunWith(AndroidJUnit4::class). I was following along with a tutorial, so I'm not 100% sure what that part does, or what this means.

The @RunWith(AndroidJUnit4::class) error is An annotation argument must be a compile-time constant

@RunWith(AndroidJUnit4::class)
class MainActivityTest {

    @get:Rule
    val activityRule = ActivityTestRule(MainActivity::class.java, true, false)

    private val mockWebServer = MockWebServer()

    @Before
    fun setup() {
        mockWebServer.start(8080)
        IdlingRegistry.getInstance().register(
            ServiceBuilder.getClient()?.let {
                OkHttp3IdlingResource.create(
                    "okhttp",
                    it
                )
            }
        )
    }

    @Test
    fun testSuccessfulResponse() {
        mockWebServer.dispatcher = object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                return MockResponse()
                    .setResponseCode(200)
                    .setBody(readStringFromFile("success_response.json"))
            }

        }
        activityRule.launchActivity(null)

        onView(withId(R.id.progress_bar))
            .check(matches(withEffectiveVisibility(Visibility.GONE)))
        onView(withId(R.id.recyclerView))
            .check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
    }

    @Test
    fun testFailedResponse() {
        mockWebServer.dispatcher = object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                return MockResponse().throttleBody(1024, 5, TimeUnit.SECONDS)
            }
        }

        activityRule.launchActivity(null)

        onView(withId(R.id.progress_bar))
            .check(matches(withEffectiveVisibility(Visibility.GONE)))
        onView(withId(R.id.recyclerView))
            .check(matches(withEffectiveVisibility(Visibility.GONE)))
    }

    @After
    fun teardown() {
        mockWebServer.shutdown()
    }
}

I'm trying to write tests that will receive a json from a mock server.


Solution

  • Turned out that I needed to put my tests in the

    androidTest/java/com/example/appname folder instead of the test/java/com/example/appname folder

    Once I moved everything it worked great!