简体   繁体   中英

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;

}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM