Home > Back-end >  Cannot resolve method 'assertThat(int)'
Cannot resolve method 'assertThat(int)'

Time:04-13

I'm following the Test Navigation docs that has the following test:

@RunWith(AndroidJUnit4.class)
public class TitleScreenTestJava {

    @Test
    public void testNavigationToInGameScreen() {

        // Create a TestNavHostController
        TestNavHostController navController = new TestNavHostController(
            ApplicationProvider.getApplicationContext());

        // Create a graphical FragmentScenario for the TitleScreen
        FragmentScenario<TitleScreen> titleScenario = FragmentScenario.launchInContainer(TitleScreen.class);

        titleScenario.onFragment(fragment ->
                // Set the graph on the TestNavHostController
                navController.setGraph(R.navigation.trivia);

                // Make the NavController available via the findNavController() APIs
                Navigation.setViewNavController(fragment.requireView(), navController)
        );

        // Verify that performing a click changes the NavController’s state
        onView(ViewMatchers.withId(R.id.play_btn)).perform(ViewActions.click());
        assertThat(navController.currentDestination.id).isEqualTo(R.id.in_game);
    }
}

First of all, this gives

Cannot resolve symbol 'currentDestination'

After some digging, I find getCurrentDestination(). I also have to change id to getId() to fix a similar error.

Then I get

Cannot resolve method 'assertThat(int)'

What version of assertThat() should I import? I found 2 versions in JUnit, but neither takes only one parameter. Besides both are deprecated. org.hamcrest.MatcherAssert has 3 versions of assertThat(), but again, none take a single int or Integer parameter. So where do I find the right version of assertThat()?

Beyond that, what am I missing here with all these changes I seem to be needed to fix the example from the official android docs? Or is this example broken?

CodePudding user response:

This is from AssertJ library.
Maven:

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.22.0</version>
    <scope>test</scope>
</dependency>

AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code readability, and is designed to be super easy to use

// basic assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);

See documentation assertThat(int)

CodePudding user response:

Use “assert” than “assertThat”.

private static boolean getBool(int i) {     return i == 0;   }
public static void main(String[] args) {
  // assert false; !will throw error
  assert true;// nothing will happen
  assert getBool(0);
  // assert getBool(1); !will throw error
}
  • Related