How to mock nested objects using mockito

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?



Read more here: https://stackoverflow.com/questions/68463132/how-to-mock-nested-objects-using-mockito

Content Attribution

This content was originally published by pvd at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: