1

I've read related SO threads, it seems that they are not applying to my specific case.

Mockito - Creating nested mock objects

mock nested method calls using mockito

We need to write some unit test cases for production code which looks like:

enter image description here

The case is:

val dbService = LevelDbKVServiceImpl()
...
dbService.insertOrUpdateAssignedField(instance, false)

And got the error:

kotlin.UninitializedPropertyAccessException: lateinit property processType has not been initialized

The chain is:

LevelDbKVServiceImpl.kt

class LevelDbKVServiceImpl {
    fun insertOrUpdateAssignedField(entity: DynamicEntity, needLogin: Boolean): Boolean {
            return LevelDbHelper.insertOrUpdateAssignedField(entity, needLogin)
    }
}

LevelDbHelper.kt

object LevelDbHelper {
    fun insertOrUpdateAssignedField(entity: DynamicEntity, needLogin: Boolean): Boolean {
        val levelDb = LevelDBHolder.of(needLogin)
        ....
    }
}

LevelDBHolder.kt

object LevelDBHolder {
    fun of(needLogin: Boolean): LevelDB {
        if(ProcessInstance.isMainProcess()){
            ....
        }
    }
}

ProcessInstance.kt

object ProcessInstance {
    private lateinit var processType: ProcessType

    // Will init it before other components
    fun init(context: Context) {
        processType = fetchProcessInfo(context)
    }

    fun isMainProcess(): Boolean {
        return processType.alias == PROCESS_MAIN_NAME
    }
}

It make sense that lateinit property processType should be initialized before test, we may need to refractor the code base to make the objects inject into other object via constructor parameters.

I was wondering is any way to use Mockito to test the insertOrUpdateAssignedField without refactoring the code base?

pvd
  • 1,303
  • 2
  • 16
  • 31

0 Answers0