2017-10-06 176 views
0
的Mockito

我對我的一些靜態字段的使用@Getter符號與龍目島這樣嘲諷龍目島田@Getter的代碼,不會:

MyClass.getMyClass(); 

嘲笑,我這樣做:

mock(MyClass.class); 
when(MyClass.getMyClass()).thenReturn(...); 

Howeve r,這樣的模擬給出了下面的錯誤。

[testng] org.mockito.exceptions.misusing.MissingMethodInvocationException: 
[testng] when() requires an argument which has to be 'a method call on a mock'. 
[testng] For example: 
[testng]  when(mock.getArticles()).thenReturn(articles); 
[testng] 
[testng] Also, this error might show up because: 
[testng] 1. you stub either of: final/private/equals()/hashCode() methods. 
[testng] Those methods *cannot* be stubbed/verified. 
[testng] Mocking methods declared on non-public parent classes is not supported. 
[testng] 2. inside when() you don't call method on mock but on some other object. 

我必須打條件2,但我不明白我不是「模擬調用方法」。

有沒有人成功地嘲笑龍目島吸氣?

謝謝!

+0

getMyClass()必須是靜態的? mockito支持靜態方法嗎? – VedX

回答

1

正如我在上面評論中所說的,Mockito不支持嘲弄靜態方法。

使用Powermock

實施例:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(A.class) 
public class YourTestClass{ 
    PowerMockito.mockStatic(A.class); 

    when(A.getMyClass()()).thenReturn(...); 

} 

此外,

MyClass.getMyClass(); 


getMyClass() belongs to class A or class Myclass ? 
+0

其實,我自己不會使用PowerMock,因爲我過去曾經有過很多痛苦,但是JMockit(http://jmockit.org/)代替了。 –