Let suppose, we have a class Employee having some private data members and public methods in it. I want to create a Junit test case to cover whether the method is called or not.
class Employee constructor(employeeName: String?){
private var isEligibleForPromotion = false
private var promotedPosition: PromotedPosition? = null
init {
try{
// checking If Employee is eligible for promotion
} catch() {}
}
fun givePromotion(employeeName: String?) {
if(isEligibleForPromotion) {
promotedPosition.promote(employeeName) //calls promote () in class PromotedPosition
}
}
}
Now, I would like to write a test case to ensure that, promotedPosition.promote() is called or not. But in order to achieve it, I need to mock the private variable isEligibleForPromotion because, I need to test it for both true & false.
Can anyone help me out in this.
I tried mocking and spying that class and private var isEligibleForPromotion. But unable to do it.
Your test case is supposed to test the
Employee
class's behavior, not its internals, so what you should mock is what the class interacts with, not its private properties. In short, setup your initial state using the inputs of the class, and assert the observable behavior of your class from outside too.You shouldn't need that. What makes this variable become true or false in the first place? You should mock the thing from outside your
Employee
class that makes this class set the variable to true or false.