Search code examples
javajunitjmockit

How to call a real method from a mocked class using jmockit


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;
    }
}

Solution

  • 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;
        }
    }