Jmockit String最终长度方法模拟问题

时间:2013-05-08 13:24:02

标签: java mocking testng jmockit

使用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;

}
}

1 个答案:

答案 0 :(得分:1)

这是记录预期结果的错误方法。您不应该模拟并记录字符串的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"));
    }