我正在构建一个 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
在我的测试的其他地方。