簡體   English   中英

在Grails中模擬私有方法

[英]Mock private method in Grails

我是新手,在集成測試中遇到困難。我有一個服務類,可以從私有方法內部調用外部服務。 有什么方法可以模擬此私有方法,以便避免集成測試的外部服務調用? 請指導我。

下面的示例代碼:

import org.springframework.web.client.RestTemplate;

public class Service {
   final static RestTemplate REST = new RestTemplate()

   def get() {      
    def list = REST.getForObject(url, clazzObject, map) 
    list
}
}

整合測試班

class RackServiceIntegrationSpec extends IntegrationSpec {
     def service = new Service()

     void testApp(){
        setup:
        def testValues = ["name1", "name2"]
        service.metaClass.get = {String url, Class clazz, Map map -> testValues}

        when:
        def val = service.get()

        then:
        val.get(0) == 'name1'

    }
}

它實際上不是原始的rest調用,而是從數據庫獲取值,而不是模擬rest調用。 我在這里做錯什么了嗎?

正如@Opal已經評論的那樣-而不是嘲笑服務的內部細節(如private方法),您應該切斷外部依賴關系。 但這當然僅適用於單元測試類型的測試。 根據測試的目標,您可以切斷外部內容,也可以進行實際調用並在另一端使用模擬程序(這都是兩個不同級別的有效測試)。

如果要在進行電匯之前進行模擬,則應使用RestTemplate的模擬實例進行模擬(這意味着必須讓其可注入-還是一個好主意,因為它是外部依賴項)。 但是spring提供了一個更好的解決方案: MockRestServiceServer

class RackServiceIntegrationSpec extends IntegrationSpec {
 def service = new Service()
   def 'service calls the external http resource correct and returns the value'() {
    setup: 'create expectations on the http interactions'
    MockRestServiceServer mockServer  = MockRestServiceServer.createServer(service.REST)
    mockServer.expect(requestTo("/customers/123")).andRespond(withSuccess("Hello world", MediaType.TEXT_PLAIN));

    when: 'service gets called'
    def val = service.get()

    then: 'http interactions were successful given the assertions above'
    mockServer.verify();

    and: 'your other assertions'
    val.get(0) == 'name1'

  }
}

有關更多信息,請參見彈簧測試文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM