> For the complete documentation index, see [llms.txt](https://notes.tejpratapsingh.com/java-testing/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.tejpratapsingh.com/java-testing/tips/how-to-test-viewmodel-and-livedata.md).

# How to test ViewModel and LiveData

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.

```java
// 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);
}
```
