-3

How can I mock and expect in JUnit for the following code?

esGateKeeper.esGateKeeper(Mockito.anyString(), "Somethin", "Something")

my full example class:

    import esGateKeeper.esGateKeeper;//external library
Class Common {

public static String getUserId(HttpServletRequest request){

        Cookie[] cookies = request.getCookies();
        String test = null;

        for (int i = 0; i < cookies.length; i++) {
            Cookie thisCookie = cookies[i];
            String cookieName = thisCookie.getName();

            if ("test".equals(cookieName)) {
                test = thisCookie.getValue();
                break;
            }
        }

        String encrypted = esGateKeeper.esGateKeeper(test, "CSP", "PROD");///unable to mock this in mockito framework
        String userId = encrypted.split("\\|")[5];
        return userId;
    }
}

till for loop its working while doing junit. after that i couldnt mock for the statement .

Sri
  • 669
  • 2
  • 13
  • 25
  • 1
    Possible duplicate of [Mocking static methods with Mockito](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – Lino Jul 27 '18 at 09:35
  • what you showed IS a mock. Can you clarify what you are struggling with? – dubes Jul 27 '18 at 09:35
  • am struggling to mock a statement in mockito esGateKeeper.esGateKeeper(Mockito.anyString(), "Somethin", "Something") – Sri Jul 27 '18 at 09:41
  • Are you looking for something like: `esGateKeeper.esGateKeeper(Mockito.anyString(), "Somethin", "Something").thenReturn("Some Value");`? – Lino Jul 27 '18 at 09:42
  • Yes.esGateKeeper is static class. so i am getting error when mocking – Sri Jul 27 '18 at 09:43
  • @Sri there exist no `static` classes in java, what type of class are you talking about? – Lino Jul 27 '18 at 09:44
  • esGateKeeper - this is external library which is static. so i want to make this statement (esGateKeeper.esGateKeeper(Mockito.anyString(), "Somethin", "Something").thenReturn("Some Value");)as mock. – Sri Jul 27 '18 at 09:46
  • @Sri there also exists no such thing as *static library* can you please clarify what you mean with `static`? – Lino Jul 27 '18 at 09:51
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/176862/discussion-between-sri-and-lino). – Sri Jul 27 '18 at 10:01

1 Answers1

1

You can use PowerMockito in conjunction with JUnit for this, here is an example

@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassWithStaticMethod.class})
public class SomeStaticMethodTest {

    @Test
    public void testSomething() {
        PowerMockito.mockStatic(ClassWithStaticMethod.class);
        when(ClassWithStaticMethod.getInstance()).thenReturn(new MockClassWithStaticMethod()); // getInstance() is a static method
        //some test condition
    }    
}

More information information here.

Cheers!

DMv2
  • 198
  • 1
  • 12