1

Say I have a class MockLoginHelper that I mocked using jmockit. And I would like to change the behaviour of one of the method getSDKConfig. Inside this method I would like to call the original LoginHelper.relogin. My eclipse thinks relogin(); below is undefined. So, how do I call a real method from a mocked class?

class MockLoginHelper extends MockUp<LoginHelper> {
    @Tested
    private SDKConfiguration config;

    @Mock
    public SDKConfiguration getSDKConfig() {
        System.out.println("");
        System.out.println("Mocked " + this.getClass().getSimpleName());
        if (config == null) {
            try {
                relogin();
            } catch (Exception e) {
                System.err.println("failed to relogin");
                e.printStackTrace();
            }
        }
        return config;
    }
}
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26
RonPringadi
  • 1,294
  • 1
  • 19
  • 44
  • Possible duplicate of [Is there a way in JMockit to call the original method from a mocked method?](http://stackoverflow.com/questions/357121/is-there-a-way-in-jmockit-to-call-the-original-method-from-a-mocked-method) – Sergii Bishyr Apr 28 '17 at 14:27

1 Answers1

1

Java compiler rightly thinks that relogin method is not in your mocked class because MockLoginHelper extends MockUp class, not LoginHelper class. You have two options. If you want to actually call real implementation of your LoginHelper then you need to instantiate a new one:

class MockLoginHelper extends MockUp<LoginHelper> {
    @Tested
    private SDKConfiguration config;

    @Mock
    public SDKConfiguration getSDKConfig() {
        System.out.println("");
        System.out.println("Mocked " + this.getClass().getSimpleName());
        if (config == null) {
            try {
                LoginHelper helper = new LoginHelper();
                helper.relogin();
            } catch (Exception e) {
                System.err.println("failed to relogin");
                e.printStackTrace();
            }
        }
        return config;
    }
}

Otherwise, you have an option of doing a mock implementation and calling that mock:

class MockLoginHelper extends MockUp<LoginHelper> {
    @Tested
    private SDKConfiguration config;

    @Mock
    public void relogin() {}

    @Mock
    public SDKConfiguration getSDKConfig() {
        System.out.println("");
        System.out.println("Mocked " + this.getClass().getSimpleName());
        if (config == null) {
            try {
                relogin();
            } catch (Exception e) {
                System.err.println("failed to relogin");
                e.printStackTrace();
            }
        }
        return config;
    }
}
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26