Skip to content

Android Basics: Write unit tests for ViewModel #277

@ottoexcellence123-tech

Description

@ottoexcellence123-tech

URL of codelab
https://developer.android.com/codelabs/basic-android-kotlin-compose-test-viewmodel?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-compose-unit-4-pathway-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-compose-test-viewmodel#3

In which task and step of the codelab can this issue be found?
Task 4: Test Strategy, all steps in this group

Describe the problem
The task doesn't describe why we're doing all these things, just how to do them. For example, Success Path step 6 is:

To get the correct player guess, use the getUnscrambledWord() function, which takes in the currentGameUiState.currentScrambledWord as an argument and returns the unscrambled word. Store this returned value in a new read-only variable named correctPlayerWord and assign the value returned by the getUnscrambledWord() function.

It is not explained where getUnscrambledWord() comes from or why we suddenly have access to it. After doing a little looking around, I found that the test package already has its own WordsData.kt, which appears to be different from the WordsData.kt in the main package. I am not sure why the GameViewModel() declared in GameViewModelTest uses the WordsData.k in the test package rather than the one in the main package.

Another example is Boundry Case step 4:

To verify the state is correct, add the assertTrue() functions to assert that the currentWordCount property is set to 1, and the score property is set to 0.

Shouldn't currentWordCount be greater than 1 since the other tests run before the Boundry Case also checkUserGuess(), which should updateGameState() and increment currentWordCount? Clearly not, otherwise the test would not succeed. So does viewModel get reset with each test? If so, this needs to be clearly explained because I am very confused and I'm sure I'm not the only one.

The lump of information at the beginning about how to write good test cases is excellent, I just wish the rest of the tutorial followed thru with technical details about using JUnit test frameworks.

Versions
Android Studio version: Android Studio Meerkat Feature Drop | 2024.3.2 Patch 1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions