airbnb / mavericks

Mavericks: Android on Autopilot
https://airbnb.io/mavericks/
Apache License 2.0
5.85k stars 499 forks source link

Add support to use Mavericks with JUnit 5 #600

Closed itsandreramon closed 2 years ago

itsandreramon commented 2 years ago

This PR adds support to use Mavericks in JUnit 5 Unit Tests by adding a MvRxExtension that is compatible with the JUnit 5 extension system, similar to JUnit 4 rules. To avoid code duplication, a new MvRxTestLifecycleCallbacks class is added, which wraps common before & after test code that is shared among the JUnit 5 Extension & JUnit 4 Rule, but can be removed if wanted. If any naming conventions are violated, please let me know.

Why? I want to run my plain Android Unit Tests with JUnit 5, since JUnit 4 is mostly only needed if running integration tests. Since you cannot use the existing MvRxTestRule in JUnit 5, I tried to copy the source in my own app and migrate it myself. I got it working pretty fast and the migration is straight forward.

Usage

import com.airbnb.mvrx.test.MvRxTestExtension
import com.airbnb.mvrx.withState
import org.junit.Assert.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension

class CounterViewModelTest {

    @Test
    fun testIncrementCount() {
        val viewModel = CounterViewModel(CounterState())
        viewModel.incrementCount()
        withState(viewModel) { state ->
            assertEquals(1, state.count)
        }
    }

    companion object {
        @JvmField
        @RegisterExtension
        val mvrxTestExtension = MvRxTestExtension()
    }
}

Additional information To run the Jupiter test one has to add support for it inside the build.gradle of the module. Since the other tests run the tests using JUnit 4, the Counter sample is modified to use the Test Extension. This way, both versions are tested.

elihart commented 2 years ago

sorry for the delay. this will be a great thing to have, we're just busy and will get to it when we can, hopefully before long.

elihart commented 2 years ago

Thanks, Detekt is failing but I'll just merge this and fix the issues myself in a followup for simplicity.