0

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?

BAERUS
  • 4,009
  • 3
  • 24
  • 39
klobin
  • 41
  • 1
  • 11
  • possible duplicate of [How can I unit test void functions?](http://stackoverflow.com/questions/21219942/how-can-i-unit-test-void-functions) – Jeroen Vannevel Aug 08 '14 at 10:09
  • As I have Stated, I have tested for that branch @MarkoTopolnik So next time I have exclude this branch :) – klobin Aug 08 '14 at 10:18
  • It would be helpfull to see how your test for that branch looks like. – A4L Aug 08 '14 at 10:19

2 Answers2

0

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.

BAERUS
  • 4,009
  • 3
  • 24
  • 39
  • It seems that it will work for me but I dont think that's a good practice to add dependency as we bought "this.getTom()" in out test code., Which will call getTom() so thus it is depended on another method to run :| – klobin Dec 09 '14 at 09:51
0

Are you calling setTom directly from your test? If so, you don't assert that all branches are covered, you just test all branches via your knowledge of the code. Call setTom twice, once with tom==null and once with tom != null. Branches covered.

John B
  • 32,493
  • 6
  • 77
  • 98
  • I don't think that by method stated by you will work ,As you told it seems to be i m just accesing the branches to increase my test coverage but I m not checking the bussiness code inside ! – klobin Dec 09 '14 at 09:47