1
我有一個對象是這樣的:階:Moking我Scala的對象具有外部依賴
// I want to test this Object
object MyObject {
protected val retryHandler: HttpRequestRetryHandler = new HttpRequestRetryHandler {
def retryRequest(exception: IOException, executionCount: Int, context: HttpContext): Boolean = {
true // implementation
}
}
private val connectionManager: PoolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager
val httpClient: CloseableHttpClient = HttpClients.custom
.setConnectionManager(connectionManager)
.setRetryHandler(retryHandler)
.build
def methodPost = {
//create new context and new Post instance
val post = new HttpPost("url")
val res = httpClient.execute(post, HttpClientContext.create)
// check response code and then take action based on response code
}
def methodPut = {
// same as methodPost except use HttpPut instead HttpPost
}
}
我想嘲弄依賴的對象像的HttpClient來測試此對象。如何實現這一目標?我可以用Mokito或其他更好的方法做到嗎?如是。怎麼樣?這個班有更好的設計嗎?
我曾想過依賴注入,但無法弄清楚如何實現。我的一個方法是將httpClient作爲每個方法的參數(因爲對象類不能像Scala那樣在Scala中具有構造函數,但Put和Post將會有新的),但是在這種情況下,我將失去對重試和其他失敗的控制案件處理。 –