1 | initial version |
In Mockito, you can set boolean field values using the when()
and thenReturn()
methods.
For example, let's say you have a class MyClass
with a boolean field myField
. You can set the value of myField
to true using the following code:
MyClass myMock = Mockito.mock(MyClass.class);
when(myMock.isMyField()).thenReturn(true);
In this example, isMyField()
is a getter method for the boolean field myField
. The when()
method sets up a stub for the method call, and thenReturn()
sets the return value to true.
You can also set the boolean field directly using reflection:
MyClass myMock = Mockito.mock(MyClass.class);
Field field = MyClass.class.getDeclaredField("myField");
field.setAccessible(true);
field.set(myMock, true);
In this example, getDeclaredField()
gets a reference to the boolean field myField
. The setAccessible()
method is called to allow access to the field, and set()
sets the value to true.