【问题标题】:Instantiate multiple spring boot apps in test在测试中实例化多个 Spring Boot 应用程序
【发布时间】:2018-05-31 16:57:53
【问题描述】:

我有几个我的 Spring Boot 应用程序实例,它们并行地对 DB 进行一些工作。每个实例都在单独的 JVM 中运行。
这是一种用 Java 编写测试以在一个 JVM 上进行测试的方法吗?如下:

  1. 设置一些嵌入式数据库用于测试目的,甚至只是模拟它。
  2. 启动我的 Spring Boot 应用程序的 2-5 个实例
  3. 请稍等
  4. 停止所有已启动的实例
  5. 验证 DB 并检查是否满足所有条件。

每个实例都有自己的上下文和类路径。
我认为我可以通过一些 shell 脚本场景来实现这一点,但我想用 Java 来实现。
这里最好的方法是什么?

【问题讨论】:

    标签: java spring unit-testing testing spring-boot


    【解决方案1】:

    您可以使用不同的端口多次运行它们。

    我做了类似的事情

    @RunWith(SpringJUnit4ClassRunner.class)
    public class ServicesIntegrationTest {
    
        private RestTemplate restTemplate = new RestTemplate();
    
        @Test
        public void runTest() throws Exception {
            SpringApplicationBuilder uws = new SpringApplicationBuilder(UserWebApplication.class)
                    .properties("server.port=8081",
                            "server.contextPath=/UserService",
                            "SOA.ControllerFactory.enforceProxyCreation=true");
            uws.run();
    
            SpringApplicationBuilder pws = new SpringApplicationBuilder(ProjectWebApplication.class)
                    .properties("server.port=8082",
                            "server.contextPath=/ProjectService",
                            "SOA.ControllerFactory.enforceProxyCreation=true");
            pws.run();
    
            String url = "http://localhost:8081/UserService/users";
            ResponseEntity<SimplePage<UserDTO>> response = restTemplate.exchange(
                    url,
                    HttpMethod.GET,
                    null,
                    new ParameterizedTypeReference<SimplePage<UserDTO>>() {
                    });
    

    here 来源。

    【讨论】:

    • 谢谢!有用。实例化 2 个 Spring Boot 应用程序副本,它可以正常运行。
    • 你可能知道的一件事。我试图区分我正在运行的应用程序,但我被困在这里。我试图添加这样的属性 - "logging.pattern.level=App-1" / "logging.pattern.level=App-2" 但它总是显示第一个 SpringApplicationBuilder.properties 中的那个。你知道为什么会这样吗?正确的区分方法是什么?
    • 可能是两件事 - 在应用配置属性之前初始化记录器。 OR 属性源的优先级高于来自 SpringApplicationBuilder 的属性。我在某处看到了用于检索值但现在找不到的源顺序。尝试谷歌。
    • 我想你误解了我的意思。第一个应用程序使用我给它的属性初始化它的记录器,没有问题。但是第二个应用程序忽略了记录器的属性。此外,我进行了一些调查,发现两个应用程序都使用相同的LoggerContext。因此,第一个应用程序使用属性中的正确值对其进行初始化,第二个应用程序看到 LoggerContext 存在并且什么也不做。
    • 我猜有一些静态/单例,所以 JVM 共享创建的实例。不知道如何排除这个:(只是在日志中包含 contextPath 以区分的解决方法
    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 2019-03-17
    • 2016-10-20
    • 2023-03-10
    • 2015-08-20
    • 2017-02-09
    • 1970-01-01
    相关资源
    最近更新 更多