繁体   English   中英

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

[英]Jmockit String final length method mocking Issue

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

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;

}
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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