我知道,我们可以在Spring-Boot中轻松地在测试范围内模拟我们的代码。在这里,我想尝试在Spring Boot中创建一个演示产品范围/配置文件。在此个人资料中,我想使用模拟场景。
例如,在我的代码中,存在第三方API调用:
String API_URL = "https://external.com/v1/%s";
private CloseableHttpClient httpClient;
public Result executeRequest(String apiVersion, String subUrl, HttpMethod httpMethod)
{
try
{
HttpRequestBase httpRequest;
String url = String.format(API_URL, subUrl);
if (httpMethod.equals(HttpMethod.GET))
{
httpRequest = new HttpGet(url);
}
else if (httpMethod.equals(HttpMethod.POST))
{
httpRequest = new HttpPost(url);
((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, "UTF-8"));
}
...
headers.forEach(httpRequest::setHeader);
HttpResponse response = httpClient.execute(httpRequest);
}
catch (IOException e)
{
logger.error("IO Error: {}", e.getMessage());
return handleExceptions(e);
}
}
是否可以在生产中模拟它?或者更好的方法;有没有办法为它创建嵌入式服务器(wiremock)?
注意:我已经在我的项目上实现了不同的配置文件属性,例如(生产,测试和开发),因此这与使用不同的配置文件无关。在这里,我只想在生产环境中模拟API,而不是在测试配置文件中模拟。当然,对于演示配置文件,我将创建demo.properties
解决方案1:
可以通过以下配置实现行为
@Configuration
@Profile("!demo")
public class ProductionConfiguration {
// Real configuration
}
@Configuration
@Profile("demo")
public class ProductionConfiguration {
// Mock configuration
}
由于@MockBean
注释是弹簧测试依赖项的一部分,因此在部署您的应用程序时它将不可用。您需要自己创建Type mockObj = Mockito.mock(Type.class)
但是这需要将mockito
依赖项打包为生成的工件的一部分。
解决方案2 :(推荐)
application-demo.properties
WireMock
服务这可确保您的生产工件不需要包含仅用于演示目的的不必要依赖关系。
[如果需要,您可以选择在WireMock
配置文件处于活动状态时启动嵌入式demo
服务器。但这意味着相关的依赖项必须是依赖项的一部分,或者可以在classpath中使用。如果可能的话,最好将WireMock作为外部服务运行。