Create instance of an Entity fo test purpose
I'm building an app, and I want to unit test all my services. I would like to avoid having an in-memory database and just have a mock implementation of my repository layer to test the services.
Right now I have this situation:
//entity
class TestEntity(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<TestEntity>(TestTable)
var test by TestTable.test
}
//repository
interface TestRepository {
suspend fun getTest(id: Int): TestEntity?
}
class TestRepositoryImpl(private val databaseRepository: DatabaseRepository) : UserRepository {
override suspend fun getTest(id: Int): TestEntity? {
return suspendedTransactionAsync(db = databaseRepository.db) {
TestEntity.findById(id)
}.await()
}
}
//service
interface TestService {
suspend fun getTest(): TestResponse
}
class TestServiceImpl(private val testRepository: TestRepository) : UserRepository {
override suspend fun getTest(): TestResponse {
val result = testRepository.getTest(1) ?: throw TestNotFoundException()
return result.toResponse()
}
}
The idea behind this is to have the opportunity to inject a test implementation of TestRepository to test the concrete implementation of TestService
I would like to do something like this:
val testRepository = object : TestRepository {
override suspend fun getTest(id: Int): TestEntity? {
//could not find a way to do that
return TestEntity().apply {
test = "test"
}
}
}
@Test
fun `do some test`() {
val result = TestServiceImpl(testRepository).getTest()
assert(result.test, "test")
}
The issue is that I could not find any way to create an instance of an entity. The only solution that I have found right now but I would like to avoid it if is possible is to wrap all the entities with data classes, but is a lot of class that represents exactly the same object.
What about DaoEntityID? I think, this could work.
@hfhbd how could work with DaoEntityID?
Update:
Ok tested that, and I got the same problem.
When I try to set some values, I have the same crash
Property klass should be initialized before get.
@raphaelbussa Did you find any solution?