I have a problem with Room test I have checked all stackoverflow solutions, but nothing works for me. I'm so beginner at test. I tried a lot of solution like change kapt and add other libraries for room
This is the Error:
java.lang.RuntimeException: cannot find implementation for com.application.unittest.data.local.ShoppingItemDatabase. ShoppingItemDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.application.unittest.data.local.ShoppingDaoTest.setup(ShoppingDaoTest.kt:40)
this is my DB class:
@Database(entities = [ShoppingItem::class], version = 1)
abstract class ShoppingItemDatabase:RoomDatabase() {
abstract fun shoppingDao():ShoppingDao
}
This is the interface:
@Dao
interface ShoppingDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertShoppingItem(shoppingItem: ShoppingItem)
@Delete
suspend fun deleteShoppingItem(shoppingItem: ShoppingItem)
@Query("SELECT * FROM shopping_items")
fun observeAllShoppingItems():LiveData<List<ShoppingItem>>
@Query("SELECT SUM(price * amount) FROM shopping_items")
fun observeTotalPrice():LiveData<Float>
}
This is the Test:
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
@SmallTest
class ShoppingDaoTest {
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private lateinit var database: ShoppingItemDatabase
private lateinit var dao: ShoppingDao
@Before
fun setup(){
database = Room.inMemoryDatabaseBuilder(
ApplicationProvider.getApplicationContext(),
ShoppingItemDatabase::class.java
)
.allowMainThreadQueries()
.build()
dao = database.shoppingDao()
}
@After
fun teardown(){
database.close()
}
@Test
fun insertShoppingItem() = runTest {
val shoppingItem = ShoppingItem(id = 1,"name",1,2f,"image")
dao.insertShoppingItem(shoppingItem)
val allShoppingItems = dao.observeAllShoppingItems().getOrAwaitValue()
assertThat(allShoppingItems).contains(shoppingItem)
}
}
So what should I do?
CodePudding user response:
Do you have an application class to instantiate the room database?
if so make sure your android manifest has this line of code under application.
<application android:name="com.application.unittest.(then you application class name)"
CodePudding user response:
The app I built recently had the same error as yours but it worked after I put the application name in the manifest. I was not using TDD or Hilt though so I am not sure if this will work or not.
But the application class I used contained this:
class MyApplication: Application() {
val database: your database class by lazy { your database class).getDatabase(this) }
}
Then make sure the application name is in the manifest. I hope this helps.