3

I have this line of code in one of the utility class

System.setProperty("someProperty", <StringValue>);

I want nothing to be happened, when the above line of code is executed through the tests. I have annotated the class with following annotations.

@PrepareForTest({KeyStore.class, System.class})
@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.security.*"})

I have tried to do nothing using following options:

1. PowerMockito.mockStatic(System.class);
   PowerMockito.doNothing().when(System.class, "setProperty", "someProperty", "stringValue");

2. PowerMockito.mockStatic(System.class);
   PowerMockito.doNothing().when(System.class, "setProperty", Mockito.any(String.class), Mockito.any(String.class));

3. PowerMockito.mockStatic(System.class);
   PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                return null; //does nothing
            }
        }).when(System.class, "setProperty", "someProperty", "stringValue");

I always get the following error on test execution.

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:

Any suggestions on how I can do nothing when System.setProperty is called. Please note System is a final class, we are calling a static method with 2 arguments. Thank you!!

theduck
  • 2,589
  • 13
  • 17
  • 23
Neha
  • 31
  • 2
  • Not sure but this might help https://stackoverflow.com/questions/9585323/how-do-i-mock-a-static-method-that-returns-void-with-powermock – tarun Jan 06 '20 at 05:51

1 Answers1

0

Only void methods can doNothing()!. setProperty() returns String

use

PowerMockito.mockStatic(System.class);
PowerMockito.when(System.setProperty(anyString(), anyString())).thenReturn("test");
CNKR
  • 568
  • 5
  • 19