如何在 @SpringBootTest 中传递程序参数?

2024-01-13

我正在构建一个 Spring Boot 应用程序。我想这样运行它:

 java -jar myjar.jar inputFile outputFile

我该如何写一个@SpringBootTest为了这?我想象使用@SpringBootTest会让 Spring 在启动过程中失败,因为我的一些代码会说,“你需要提供一个 inputFile 和 outputFile”。有没有办法在使用时传递程序参数@SpringBootTest?

我从这个答案推断 https://stackoverflow.com/a/36807196/61624我可能必须使用 SpringApplicationBuilder 来执行此操作。

I thought我已经有了答案,但我错了。这些不正确的信息可能对某些人仍然有用:


(此信息是错误的。我认为某些参数不能在代码中作为属性引用,但不是全部。我仍然不知道如何获取应用程序参数@SpringBootTest)我很困惑,因为我不明白这些术语。注释有一个“属性”参数。我以为是把它指向一个属性文件,但文档说 https://stackoverflow.com/a/36807196/61624:

key=value 形式的属性应在测试运行之前添加到 Spring 环境中。

术语难题的另一个部分是我所说的“程序参数”,Spring 文档将其称为“属性”。

这是一些额外的相关文档:https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-arguments https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-application-arguments


这是一种解决方法(不是答案)。你可以这样做:

private SpringApplicationBuilder subject;

@Before
public void setUp() throws Exception {
    subject = new SpringApplicationBuilder(Application.class);
}

@Test
public void requiresInputAndOutput() throws Exception {

    thrown.expect(IllegalStateException.class);
    subject.run();
}

@Test
public void happyPathHasNoErrors() throws Exception {

    subject.run(EXISTING_INPUT_FILE, "does_not_exist");
}

我不太喜欢这个。它阻止我使用@Autowired在我的测试的其他地方。


如果你的程序参数是

--arg1=val1

Spring Boot 2.2.0 版本之前 您可以使用

@SpringBootTest({"arg1=val1"})

春季启动2.2.0之后 您可以使用

@SpringBootTest(args={"--arg1=val1"})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 @SpringBootTest 中传递程序参数? 的相关文章

随机推荐