Search code examples
javajunitmockitotestcase

How to test a call is made to void method with nothing to assert inside that


In the code below I have covered one of two branches of an if statement. But I also want to test the other branch, i.e. when this.tom != null.

public void setTom(boolean cmsConsent, boolean ebConsent) {
    if(this.tom== null){
        this.tom= new Tom(cmsConsent,ebConsent);
    }
}

How to write assert statement so that all branches are covered?


Solution

  • It seems that your field "tom" is a simple private field? If it doesn't get injected, you can't mock it to be or not to be null.

    I guess you also have a Getter for that tom object? If you would change your code from:

    if(this.tom== null){
    

    to

    if(this.getTom() == null){
    

    than you could mock the Getter away using Mockito's SPY functionality. (If you are willing to do so I can explain further)

    PS: PowerMock(ito) is always a possibility to enhance your code by byte manipulation, but it should only be used when necessary imo.