Objects behave weird when mocking private method of class under test using jmockit

154 views Asked by At

Instance object of my class under test behavior varies when I tried to mock private method of my class. I have object of my CUT which I am initializing in @Before setup method

@Before
public void setUp() {
    cutInstance = new CUT();

and in my test method I mocked CUT by creating local object of CUT

@Test
public void test_someMethod(@Mocked CUT cutInstanceLocal)

then mocking private method of CUT using Expectations API

new Expectations(cutInstanceLocal) {{
    Deencapsulation.invoke(cutInstanceLocal, "cutPrivateMethod", value);
    result = fakeValue;
}};

now testing the cutMethod(param) which will internally call mocked method.

now on testing, sometimes I got param's value as null, which is weird.

Why it is happening so ?

1

There are 1 answers

0
Josef.B On

You are not using JMockit correctly. First you don't need to use deencapsulate. JMockit can mock private methods. Second, in the Expectations you should specify the expectation on dependent classes, not on the class under test (CUT).

If all you want to do is mock a method of the CUT just mock it:

new MockUp<CUT>(){
      public Object cutPrivateMethod(Object value){
         return fakeValue;
      }
};

Even if cutPrivateMethod was private in the CUT class, it would get mocked.