生产中的Spring Boot API模拟

问题描述 投票:2回答:1

我知道,我们可以在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

java spring-boot production-environment demo embedded-server
1个回答
1
投票

解决方案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 :(推荐)

  • 将API URL外部化为属性文件。
  • 创建用于演示目的的单独的属性文件application-demo.properties
  • 更新此属性文件中的URL以连接到外部WireMock服务

这可确保您的生产工件不需要包含仅用于演示目的的不必要依赖关系。

[如果需要,您可以选择在WireMock配置文件处于活动状态时启动嵌入式demo服务器。但这意味着相关的依赖项必须是依赖项的一部分,或者可以在classpath中使用。如果可能的话,最好将WireMock作为外部服务运行。

© www.soinside.com 2019 - 2024. All rights reserved.