Get immediate access to this and 4,000+ other videos and books.

Take your career further with a raywenderlich.com Pro subscription. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it’s simply the best investment you can make in your development career.

Test the ViewModel Pro

You’ll need to add the mockito-inline dependency because you could get into some issues when trying to moch the CreatureGenerator class. This is added in the final project in the download materials.

Use JUnit to add unit tests for the functionality of the ViewModel layer, while utilizing Mockito to mock dependent classes.

Contributors

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

You can unlock the rest of this video course, and our entire catalogue of books and videos, with a raywenderlich.com Professional subscription.

When testing the model layer, we used TDD. For the view model, we’ll now add an after-the-fact test for the view model we’ve just created.

  testImplementation "org.mockito:mockito-core:2.11.0"
testImplementation "android.arch.core:core-testing:$arch_comp_version"
class CreatureViewModelTest {
}
  private lateinit var creatureViewModel: CreatureViewModel
  @get:Rule
  var rule: TestRule = InstantTaskExecutorRule()
  @Mock
  lateinit var mockGenerator: CreatureGenerator
  
  @Before
  fun setup() {
    MockitoAnnotations.initMocks(this)
    creatureViewModel = CreatureViewModel(mockGenerator)
  }
  @Test
  fun testSetupCreature() {
    val attributes = CreatureAttributes(10, 3, 7)
    val stubCreature = Creature(attributes, 87, "Test Creature")
    `when`(mockGenerator.generateCreature(attributes)).thenReturn(stubCreature)
    
    creatureViewModel.intelligence = 10
    creatureViewModel.strength = 3
    creatureViewModel.endurance = 7
  }
 
    creatureViewModel.updateCreature()
   
    assertEquals(`stubCreature`, creatureViewModel.creature)

Reviews

Comments