Search code examples
javamockingtestngjmockit

Jmockit String final length method mocking Issue


Using jmockit 1.2 jar, Trying to mock String's length method but getting Unexpected Invocation Exception:

FAILED: test
java.lang.IllegalStateException: Missing invocation to mocked type at this point;      please make sure such invocations appear only after the declaration of a suitable mock   field or parameter
at StringDemo.TestA$1.<init>(TestA.java:17)
at StringDemo.TestA.test(TestA.java:13)

I am using testNG:

@Test
   public void test() throws Exception
   {
    new Expectations()
      {
        @Mocked("length")
        String aString;
         {
            aString.length();
            result = 2;
         }
      };

      System.out.println(A.showA("test"));
   }
}

Actual class A:

public class A {
public static int showA(String str){
    int a= str.length();
    return a;

}
}

Solution

  • This is the wrong way of recording the expected results. You shouldn't mock and record String's length() method, record your showA() instead. here is the solution

        @SuppressWarnings("unused")
        @Test
        public void test() throws Exception
        {
    
            new Expectations()
            {
                @NonStrict
                final Source mock = null;
    
                {
                    Source.showA(anyString);
                    result = 2;
                }
            };
    
            assertEquals(2, Source.showA("test"));
        }