Home > Software engineering >  How to mock protected global variables boolean in java junit test
How to mock protected global variables boolean in java junit test

Time:02-03

How to mock protected global variables boolean in java junit test

public abstract class Base {
  protected boolean varBoolean;

  ...

}


public class NameClass extends Base {

   public void init() {

      if (varBoolean) {

         ...

      }

      ...

   }

}

@RunWith(JUnit4.class)
@Slf4j
public class NameClassTest {

  ...

}

How to mock protected varBoolean be equal true in java unit test.

CodePudding user response:

I can fix it.

@RunWith(JUnit4.class)
@Slf4j
public class NameClassTest {

 @InjectMocks
 NameClass nameClass;


 @Test
 public void testInit() throws Exception {
    nameClass.varBoolean = true;
    nameClass.init();
    ...
 }

}

nameClass.varBoolean = true;

Thank you for help me. :-)

CodePudding user response:

Add a test only constructor to NameClass with a varBoolean parameter. Call it in your test with whatever argument you want.

  • Related