2013-05-08 149 views
2

使用jmockit 1.2罐子, 試圖嘲笑字符串的長度的方法,但得到意外的調用異常:Jmockit字符串最終長度方法嘲諷問題

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

這是記錄預期的錯誤方法結果。你不應該模擬和記錄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")); 
    } 
+0

是啊,我這樣做,只是以前。但是,因爲我能夠模擬getBytes方法的String,所以我認爲它應該也適用於長度。你能告訴我爲什麼它不適用於長度方法的確切原因嗎? – solvesak 2013-05-09 13:16:45

+2

'String#length()'方法是少數不能被JMockit 1.x嘲笑的方法之一。這組不可模擬的JRE方法存在的原因是,如果嘲笑它們,會導致JMockit 1.x中出現問題。 – 2013-05-17 11:49:17

+0

@Rogério - 這很好。它在任何地方記錄? – 2013-05-22 17:55:58