Test ViewModel In MVVM model (RxSwift)

Tram Ho

The ViewModel test is that we conduct tests for the ViewModel part in models containing ViewModel like MVVM or MVVC-C, etc. That means your project must apply one of those models. If you’ve never applied or learned about it, please read here or here

This is not a technique or method, but simply we use techniques such as Mock, Stub, Fake, … to test ViewModel – the main logic processing in the app. So this section will guide an example, bringing the most typical characteristics of the ViewModel section so that we can easily visualize the Test ViewModel as well as writing UnitTest in general.

These characteristics may include:

  • Declaring and setting up related components
  • Use Mock, Stub to build replacement components
  • Write and run function tests

For example:

We have 1 ViewModel with 1 function getData ():

With UseCase is separated as follows:

Declaring and setting up related components

First, we create the test file, if you do not know then you can refer here. And proceed to declare as follows:

Note: If importing modules from a pod, we must make sure that the modules have been added to the target test in the Podfile file.

For example:

Use Mock, Stub to build replacement components

Above, we have MyUseCaseMock, used to replace MyUseCase, the entire class has been trimmed as follows:

Write and run function tests

After all the components have been prepared, we proceed to write the function tests. Because in the new viewmodel only getData () function, we have the following function:

At Class Test:

Explanation: The above function test has checked if the data of the getData () function returns nil. If nil, when we run the function will fail and vice versa.

Or further, we can test to see if the getData () function is called at the beginning, using the MyUseCaseMock section that was written earlier:

By using XCTAssert and in conjunction with test support techniques, we will build function tests for functions in ViewModel. Thank you for reading my article. Hope it helps you in the process of learning about UnitTest

Share the news now

Source : Viblo