2017-07-03 97 views
0
的Mockito

所以我遷移少量的Java代碼庫科特林只是爲了好玩,我已經遷移這個Java類:嘲諷科特林方法與Java +

public class Inputs { 
    private String engineURL; 
    private Map<String, String> parameters; 

    public Inputs(String engineURL, Map<String, String> parameters) { 
     this.engineURL = engineURL; 
     this.parameters = parameters; 
    } 

    public String getEngineURL() { 
     return engineURL; 
    } 

    public String getParameter(String key) { 
     return parameters.get(key); 
    } 
} 

這個科特林表示:

open class Inputs (val engineURL: String, 
        private val parameters: Map<String, String>) { 

    fun getParameter(key: String?): String { 
     return parameters["$key"].orEmpty() 
    } 

} 

但是現在我在使用Java編寫的現有測試套件時遇到了一些麻煩。更具體地講,我有這片單元測試使用的Mockito:

@Before 
public void setupInputs() { 
    inputs = mock(Inputs.class); 
    when(inputs.getEngineURL()).thenReturn("http://example.com"); 
} 

,並在when線路出現故障時,說

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'. 
For example: 
    when(mock.getArticles()).thenReturn(articles); 

Also, this error might show up because: 
1. you stub either of: final/private/equals()/hashCode() methods. 
    Those methods *cannot* be stubbed/verified. 
    Mocking methods declared on non-public parent classes is not supported. 
2. inside when() you don't call method on mock but on some other object. 

有誰知道我怎麼會做這項工作?我已經嘗試在Kotlin版本上創建一個實際的getter(而不是依賴隱式getter),但到目前爲止沒有運氣。

非常感謝! (如果你問自己,爲什麼我要從產品代碼開始而不是測試,或者爲什麼我不使用mockito-kotlin,這些問題沒有真正的答案。就像我說的,我只是爲了遷移而遷移樂趣和希望,以顯示我的團隊其他開發人員是多麼容易在實際項目中的語言)之間的互操作性

更新:我發現如果我添加when(inputs.getParameter("key")).thenReturn("value")相同的setupInputs()方法(inputs.getEngineURL())調用之前)我最終在Inputs#getParameter處發生了NullPointerException。 WTF?

+0

對於記錄:這裏的科特林代碼缺少的getEngineUrl()方法。所以你的例子不是[mcve]。隨時更新;那麼我會覺得喜歡upvoting你的輸入;-) – GhostCat

+0

@GhostCat我不知道我跟着它,畢竟'getEngineUrl()'是由基於'val engineURL:String'構造函數參數的Kotlin自動提供的,不是嗎? – felipecao

+0

那麼,你可能有一個點;-) – GhostCat

回答

1

沒關係,我把他與兩個錯誤消息,通過重寫科特林版本是這樣的:

open class TransformInputs (private val eURL: String, 
          private val parameters: Map<String, String>) { 

    open fun getParameter(key: String?): String { 
     return parameters["$key"].orEmpty() 
    } 

    open fun getBookingEngineURL(): String { 
     return eURL 
    } 

} 
+0

你也可以避免讓你的課堂不必要地在Mockito 2中打開:http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/ –

+0

Thx @JKLy!我實際上已經考慮到了這一點,但我不想爲了使其與Kotlin一起工作而更改現有的代碼庫。我的想法是向團隊表明,使用Kotlin是可能的,只需要很少的更改,所以我故意忽略Mockito版本。 – felipecao