0

Searched on google about, how to mock a variable in unit testing and seen some suggestions, for my case its not working. my scenario is,

class Keys {

private static Keys sKeys;
private String enKey = null;

static synchronized sKeys getInstance() {
    if(sKeys == null) {
        sKeys = new Keys();
    }
    return sKeys;
}

Boolean isLocked() {
    if(enKey == null ) {
        return true;
    }
    return false;
  }
}

This is the class, i have written. Unit test of the class is below,

@RunWith(MockitoJUnitRunner.class)     
public class KeysTest {

@Test
public void isLocked_Test() {
    Keys key = Keys.getInstance();
    Key.isLocked();
   // Here in isLocked function I want to mock the enKey value to other than null
   }
}

Here, i want to call isLocked function, and i want to set or mock the enKey variable value to other than null.

How i can do that? Could anyone help me on that?

Happy
  • 1,031
  • 10
  • 26

1 Answers1

1

To mock a static you will need to use PowerMock or a similar library.

Please see this question and answer.

Alternatively you could use the method described below after refactoring out the static design (if desired).

To create a mock using Mockito,

MyClass myMock = Mockito.mock(MyClass.class);

To set the return value of a specific function for a mocked class,

when(myMock.myFunc()).thenReturn(desiredValue);

Be sure to review the documentation as well.

Tim F.
  • 290
  • 2
  • 16
  • 1
    The example you said is not, myMock.myFunc() is not returning the mentioned value. and i don't want to mock a function. i want to mock the variable. This variable (enKey), i want to mock it as other than null. – Happy Apr 20 '18 at 03:51