2

使用 jmockit 1.2 jar,尝试模拟 String 的长度方法但得到意外调用异常:

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)

我正在使用 testNG:

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

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

实际A类:

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

}
}
4

1 回答 1

1

这是记录预期结果的错误方式。你不应该模拟和记录 String 的length()方法,showA()而是记录你的。这是解决方案

    @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"));
    }
于 2013-05-09T11:08:13.423 回答