Java Jmockit字符串最终长度方法模拟问题
使用jmockit 1.2 jar, 尝试模拟字符串的长度方法,但出现意外调用异常:Java Jmockit字符串最终长度方法模拟问题,java,mocking,testng,jmockit,Java,Mocking,Testng,Jmockit,使用jmockit 1.2 jar, 尝试模拟字符串的长度方法,但出现意外调用异常: 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
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)
实际A类:
public class A {
public static int showA(String str){
int a= str.length();
return a;
}
}
这是记录预期结果的错误方式。您不应该模拟并记录字符串的
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"));
}
是的,我以前才这么做过。但由于我能够模拟字符串的getBytes方法,所以我认为它应该也适用于长度。你能告诉我它不适用于length方法的确切原因吗?
String#length()
方法是JMockit 1.x无法模仿的少数方法之一。这组不可模拟的JRE方法之所以存在,是因为众所周知,如果对它们进行模拟,它们会在JMockit 1.x中导致问题。@Rogério-很高兴知道这一点。它在任何地方都有记录吗?它没有记录,因为没有一个好的地方插入这样的细节,主要是因为它不应该在第一个地方出现。模拟像String#length()
这样的方法通常不应该这样做。
@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"));
}