2016-05-13 141 views
1

我有Grails rest api应用程序,它通过服务在内部调用外部休息API。我想在执行集成测试用例时模拟外部API调用服务。在集成测试用例中,我将请求发布到应用程序rest api。由于我无法模拟外部API,因此如果外部API无法访问,则会失败。 那么如何在集成测试用例中模拟调用外部API的服务。嘲笑Grails Spock集成测试

+0

没有任何代码我们如何能够建议问题在哪里。 –

回答

0

在您的配置中包含外部API的URL,以便您可以嘲笑它,假设它的配置密钥被称为myConfigValue。安装WireMock,包括测试服务器作为JUnit规则:

@Rule 
WireMockRule mockServer = new WireMockRule(WireMockConfiguration.wireMockConfig().port(9900)) 

订阅模拟服务器的URL到您的测试就像在the Grails manual描述:

static doWithConfig(c) { 
    c.myConfigValue = "http://localhost:9900/" 
} 

然后使用WireMock的API来验证外部调用和存根回应,例如

stubFor(get(urlEqualTo("/binary-body")) 
    .willReturn(aResponse() 
    .withBody(new byte[] { 1, 2, 3, 4 }))); 

检查他们的文档,了解什么是可能的。 WireMock有其他选择,但没有一个为我们工作得很好。

+0

作为WireMock的替代品,下面是使用其他库Ratpack测试Grails 3应用程序的博客文章:http://kyleboon.org/blog/2015/07/18/stubbing-service-interactions-when-testing-microservices / –