Dan*_*lan 6 java spring spring-boot
我正在构建一个 Spring Boot 应用程序。我想这样运行它:
java -jar myjar.jar inputFile outputFile
Run Code Online (Sandbox Code Playgroud)
我该如何@SpringBootTest为此写一个?我想使用@SpringBootTest会使 Spring 在启动过程中失败,因为我的一些代码会说,“你需要提供一个 inputFile 和 outputFile”。使用 时有没有办法传递程序参数@SpringBootTest?
我从这个答案推断我可能必须使用 SpringApplicationBuilder 来做到这一点。
我以为我已经有了答案,但我错了。这些不正确的信息可能对某些人仍然有用:
(此信息是错误的。我认为某些参数不能在代码中作为属性引用,但不是全部。我仍然不知道如何在 a 中获取应用程序参数@SpringBootTest)我很困惑,因为我不明白术语。注释有一个“属性”参数。我以为是将其指向属性文件,但文档说:
key=value 形式的属性应在测试运行之前添加到 Spring 环境中。
术语难题的另一个部分是我所说的“程序参数”,Spring 文档将其称为“属性”。
这是一种解决方法(不是答案)。你可以这样做:
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");
}
Run Code Online (Sandbox Code Playgroud)
我不太喜欢这个。@Autowired它阻止我在测试中的其他地方使用。
小智 10
如果你的程序参数是
--arg1=val1
Run Code Online (Sandbox Code Playgroud)
springboot 2.2.0版本之前你可以使用
@SpringBootTest({"arg1=val1"})
Run Code Online (Sandbox Code Playgroud)
springboot 2.2.0之后你可以使用
@SpringBootTest(args={"--arg1=val1"})
Run Code Online (Sandbox Code Playgroud)
通常,您正在为您的服务编写测试;不是引导捆绑器。Spring Boot 会将命令行参数传递给您的类 - 可能使用 @Value 注释,这反过来又将成为您的服务的参数。考虑使用 SpringRunner 测试您的服务。这是我的代码库中的一个示例。
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
Neo4jConfigTest.class,
FdTemplate.class,
FdServerIo.class,
MapBasedStorageProxy.class})
@ActiveProfiles({"dev", "fd-auth-test", "fd-client"})
public class TestEntityLinks {
@Autowired
private ContentModelService contentModelService;
@Autowired
private BatchService batchService;
@Test
public void doSomething () { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17797 次 |
| 最近记录: |