can we set variables in a class under test to desired values, something like stubbing?

73 Views Asked by At

i want to test if the flow of control in a class under test is working as expected.

from the test class, boolean variables would be set to different combinations of true or false.

instead of line 1 below, is there something like lines 2 and 3?

  1. when(listMock.add(anyString())).thenReturn(false)

  2. setValueToVariableInClassUnderTest(sendAlert,true)

  3. setValueToVariableInClassUnderTest(sendAlert,false)

2

There are 2 best solutions below

0
sprinter On

From your comment:

the variables like sendAlert is set with values in a configuration file like this: @Value(${path.to.value.in.confile.file}) \n private boolean sendAlert. i don't think it has getter and setter methods.....

It seems as though the class you are testing is not designed to be easily testable. It would be far better if it has a dependency on a configurator that reads from a file if that configurator was passed to it and could, therefore, be mocked.

Your best option if you are not able to change the class under test would be to mock the configuration file as part of your test. By doing that you are testing the class using its intended interface. Using backdoors (e.g. using reflection to break encapsulation) will leave you with fragile tests.

0
subasri_ On

You can use ReflectionTestUtils to set value of a non-public field that has no public setter method.

ReflectionTestUtils.setField(targetObject, "sendAlert", true);