File tree Expand file tree Collapse file tree 2 files changed +27
-8
lines changed
androidTestMock/java/com/example/android/architecture/blueprints/todoapp/tasks
mock/java/com/example/android/architecture/blueprints/todoapp Expand file tree Collapse file tree 2 files changed +27
-8
lines changed Original file line number Diff line number Diff line change @@ -33,6 +33,7 @@ import androidx.test.espresso.matcher.ViewMatchers.withId
33
33
import androidx.test.espresso.matcher.ViewMatchers.withText
34
34
import androidx.test.ext.junit.runners.AndroidJUnit4
35
35
import androidx.test.filters.LargeTest
36
+ import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
36
37
import com.example.android.architecture.blueprints.todoapp.R
37
38
import com.example.android.architecture.blueprints.todoapp.R.string
38
39
import com.example.android.architecture.blueprints.todoapp.ServiceLocator
@@ -67,13 +68,19 @@ class TasksActivityTest {
67
68
68
69
@Before
69
70
fun init () {
70
- repository = ServiceLocator .provideTasksRepository(getApplicationContext())
71
- repository.deleteAllTasksBlocking()
71
+ // Run on UI thread to make sure the same instance of the SL is used.
72
+ runOnUiThread {
73
+ ServiceLocator .createDataBase(getApplicationContext(), inMemory = true )
74
+ repository = ServiceLocator .provideTasksRepository(getApplicationContext())
75
+ repository.deleteAllTasksBlocking()
76
+ }
72
77
}
73
78
74
79
@After
75
80
fun reset () {
76
- ServiceLocator .resetRepository()
81
+ runOnUiThread {
82
+ ServiceLocator .resetRepository()
83
+ }
77
84
}
78
85
79
86
/* *
Original file line number Diff line number Diff line change @@ -55,11 +55,23 @@ object ServiceLocator {
55
55
return TasksLocalDataSource (database.taskDao())
56
56
}
57
57
58
- private fun createDataBase (context : Context ): ToDoDatabase {
59
- val result = Room .databaseBuilder(
60
- context.applicationContext,
61
- ToDoDatabase ::class .java, " Tasks.db"
62
- ).build()
58
+ @VisibleForTesting
59
+ fun createDataBase (
60
+ context : Context ,
61
+ inMemory : Boolean = false
62
+ ): ToDoDatabase {
63
+ val result = if (inMemory) {
64
+ // Use a faster in-memory database for tests
65
+ Room .inMemoryDatabaseBuilder(context.applicationContext, ToDoDatabase ::class .java)
66
+ .allowMainThreadQueries()
67
+ .build()
68
+ } else {
69
+ // Real database using SQLite
70
+ Room .databaseBuilder(
71
+ context.applicationContext,
72
+ ToDoDatabase ::class .java, " Tasks.db"
73
+ ).build()
74
+ }
63
75
database = result
64
76
return result
65
77
}
You can’t perform that action at this time.
0 commit comments