0

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.

  • how is `promotedPosition` initialized? – sidgate Nov 23 '22 at 10:04
  • How is `isEligibleForPromotion` initialized? – Joffrey Nov 23 '22 at 10:29
  • @sidgate, `PromotedPosition` is basically an interface which is defined by some other method, inside the `init{}` block. – Coding_yatra Nov 23 '22 at 12:04
  • 1
    Looks like you might be doing a lot in the `init` block. It's an important piece to share in order to answer this question better. Trying to mock the private property is most likely an [XY problem](https://xyproblem.info/), and information about how to do X is in this `init` block implementation – Joffrey Nov 23 '22 at 13:18

1 Answers1

0

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.

in order to achieve it, I need to mock the private variable isEligibleForPromotion

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.

Joffrey
  • 32,348
  • 6
  • 68
  • 100
  • Yes @Joffrey, it makes sense that we should create the mock thing from outside the `Employee` class. But what makes it difficult is, if in init{} block the value `isEligibleForPromotion` is based on some business logic from some 3rd party library and apart from that it is not returning anything. Thus, we don't have any idea on implementation for that. – Coding_yatra Nov 23 '22 at 12:02
  • @Coding_yatra if the `init` block gets information from outside, why not mock the thing it gets information from? – Joffrey Nov 23 '22 at 13:16