Exposed icon indicating copy to clipboard operation
Exposed copied to clipboard

Create instance of an Entity fo test purpose

Open raphaelbussa opened this issue 4 years ago • 4 comments

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.

raphaelbussa avatar Jan 16 '22 18:01 raphaelbussa

What about DaoEntityID? I think, this could work.

hfhbd avatar Jan 16 '22 19:01 hfhbd

@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 avatar Jan 16 '22 21:01 raphaelbussa

@raphaelbussa Did you find any solution?

hennihaus avatar Sep 15 '22 11:09 hennihaus