[英]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.