Notes
Java Testing
Java Testing
  • Java Testing
  • Mockito
    • Mockito.mock()
    • Mockito.spy()
    • Mockito.verify()
    • Mockito.mockStatic()
    • ArgumentMatcher
    • ArgumentCaptor
  • PowerMockito
    • Why we need PowerMock?
    • PowerMockRunner
    • PrepareForTest
      • Understanding @PrepareForTest
    • SuppressStaticInitializationFor
    • PowerMockito.suppress()
    • PowerMockito.stub()
    • PowerMockito.replace()
    • PowerMockito.whenNew()
      • Limitation of PowerMockito.whenNew()
    • Whitebox.invokeMethod()
    • Whitebox.setInternalState()
    • Whitebox.getInternalState()
  • Tips
    • How to test ViewModel and LiveData
Powered by GitBook
On this page
  1. Tips

How to test ViewModel and LiveData

Test your async code build on top of androidx arch.

As tests are synchronous in nature. To test async code, we need to let compiler know we need to call all async code synchronously.

We can set a custom delegate to execute all of our async code as soon as it is called. hence making it syncronous.

// Some code
@BeforeClass
public static void beforeClass() throws Exception {
    TaskExecutor taskExecutor = new TaskExecutor() {
        @Override
        public void executeOnDiskIO(@NonNull Runnable runnable) {
            runnable.run();
        }

        @Override
        public void postToMainThread(@NonNull Runnable runnable) {
            runnable.run();
        }

        @Override
        public boolean isMainThread() {
            return true;
        }
    };
    ArchTaskExecutor.getInstance().setDelegate(taskExecutor);
}

@AfterClass
public static void afterClass() throws Exception {
    ArchTaskExecutor.getInstance().setDelegate(null);
}
PreviousTips

Last updated 1 year ago