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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.tejpratapsingh.com/java-testing/tips/how-to-test-viewmodel-and-livedata.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
