Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return same value for every instance of a method call

Tags:

java

mockito

Hi I'm not using PowerMockito but normal one and trying to mock something like this:

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

But I get a NullPointerException. Basically without mocking a specific instance I want to mock any and all instances of a file object to return FALSE for canWrite().

Can anyone help? I can mock the object but the code I'm testing is inside a static method.

like image 540
Forrie Avatar asked Jul 19 '26 06:07

Forrie


1 Answers

This is not possible. With regular Mockito you need some mock object in the when() call, not an any matcher.

For your example, when you say any(File.class)

when(any(File.class).canWrite()).thenReturn(Boolean.FALSE)

You need to have a file object already instantiated as a Mock

File fileMock = mock(File.class);    
when(fileMock.canWrite()).thenReturn(Boolean.FALSE)
like image 59
Jason D Avatar answered Jul 25 '26 07:07

Jason D