【问题标题】:How to programatically instantiate a spring boot test?如何以编程方式实例化 Spring Boot 测试?
【发布时间】:2019-06-09 19:57:27
【问题描述】:

我希望在代码中实例化一个 Spring Boot 测试。

我有一组黄瓜测试,它使用@SpringBootTest 实例化我的应用程序的弹簧上下文,但我现在希望利用相同的测试和步骤代码,但要针对我部署的应用程序运行。

所以我期待:

  • 检查系统属性
  • 如果设置了系统属性,则在SpringBootTest 环境中实例化我的本地上下文
  • 实例化一个不同的SpringBootTest 上下文,它会命中我的服务的实时实例。

有人对如何做到这一点有任何建议吗?

附:

我使用 spring boot 作为我的服务,junit4 和 maven。

【问题讨论】:

标签: java spring spring-boot junit4


【解决方案1】:

Ovarall,所有 Junit 测试设置仍在 Spring Boot 中工作。

  1. 您可以在整体测试之前使用以下方法进行设置/配置

    @BeforeClass 公共静态无效 setUpClass() { System.out.println("@BeforeClass setUpClass"); myExpensiveManagedResource = new ExpensiveManagedResource(); }

    @AfterClass 公共静态无效 tearDownClass() 抛出 IOException { System.out.println("@AfterClass tearDownClass"); myExpensiveManagedResource.close(); myExpensiveManagedResource = null; }

  2. 你也可以为每个方法做配置

    @之前 公共无效设置(){ this.println("@Before 设置"); this.myManagedResource = new ManagedResource(); }

    @之后 public void tearDown() 抛出 IOException { this.println("@After tearDown"); this.myManagedResource.close(); this.myManagedResource = null; this.println(" "); }

【讨论】:

  • 我的目标是根本不实例化我的上下文,因为这需要打开端口、连接到数据库、kafka 等。
  • 如果我正确理解您的问题,您可以在 @BeforeClass 方法中摄取您的实时服务实例。
猜你喜欢
  • 2019-10-28
  • 1970-01-01
  • 2013-08-11
  • 2018-05-31
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2011-02-26
  • 2015-05-18
相关资源
最近更新 更多