-2

So here is the scenario

public class Report {

    public void Generate {
       if (!isValidDate) {
       return;
       }

       //calling other method
    }

    protected boolean isValidDate() {
       boolean isValid = true;
       //some logic here to change to false
       return isValid;
    }
}

And in my test, I have this as I want to set the boolean value to be true.

@InjectMocks
Report report;

@Before
public void setUp() throws Exception {
    Whitebox.setInternalState(report, "isValidParameters", true);
}

@Test
public void testReport() throws Exception {
    //test logic to be added here
}

Then I got the RuntimeException: Unable to set internal state on a private field. Can someone please help on how I can set the boolean value of that protected method for my test here? TIA

J.TrLu
  • 65
  • 1
  • 12

1 Answers1

0

If you want to learn to write unit tests one of the best things you can do is stop using Powermockito.

A protected method that you want to test by it self is a sign that your class may have too many responsibilities and needs to be refactored.

Instead of the method, why not use the extract object pattern?

public class DateValidator {
    public boolean isValid(Date date) {
        //previous logic from protected method goes here
    }
}

Then you can pass this into the constructor for your class:

public class Report {

    private final DateValidator dateValidator;

    public Report(DateValidator dateValidator) {
        this.dateValidator = dateValidator;
    }
}

Now your test can look like this:

@Mock DateValidator mockDateValidator;

//system under test
Report report;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    report = new Report(mockDateValidator);
}

@Test
public void test() throws Exception {
    when(mockDateValidator.isValid()).thenReturn(true);

    //your test here
}

Sticking with plain Mockito is a good discipline that will teach you good OOP practices. The Mocktio documentation is very good for explaining this and you could benefit a lot by reading it.

David Rawson
  • 20,912
  • 7
  • 88
  • 124