Ask Your Question
3

How can boolean field values be set using Mockito?

asked 2023-07-11 01:45:26 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-11 01:50:01 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-11 01:45:26 +0000

Seen: 10 times

Last updated: Jul 11 '23