测试 Spring 上下文甚至不应该加载的情况
Test Spring for case when context should not even load
我想测试我的 Spring 引导应用程序在没有给出配置文件的情况下的情况。在这种情况下,应用程序在创建 bean MyConfig
.
时应该抛出异常
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public MyConfig myConfig() throws IOException {
if (no config file) throw new NoConfigFileException();
}
}
我有一个测试是否构建了 Spring 应用程序的上下文:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@TestPropertySource(locations="classpath:file_with_existing_config_file_path.properties")
public class MyApplicationTest {
@Test
public void contextLoads() {
}
}
此测试失败 - 正如预期的那样(因为 myConfig
方法抛出 NoConfigFileException
)。不幸的是我不能 "turn the light to green" 使用注释 @Test(expected = NoConfigFileException.class)
.
如果不是在我得到的唯一一种测试方法中,我应该在哪里期待异常?
编写自动化测试的黄金法则是 -> 每个测试方法覆盖一个测试用例(除非您进行参数化测试)。在我看来,你正在考虑打破那个规则。
考虑单独测试 class(您不指定属性文件),它仅测试这方面或您的逻辑。这样你就可以使用 @Test(expected = NoConfigFileException.class)
.
顺便说一句,我建议查看 Spring 引导功能 @ConfigurationProperties。您可以对您的属性使用 Java EE 验证(例如 @NotNull)。
如果没有配置文件加载到 Spring 上下文中,您可以强制应用程序查找文件并尽早失败。
我想测试我的 Spring 引导应用程序在没有给出配置文件的情况下的情况。在这种情况下,应用程序在创建 bean MyConfig
.
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
@Bean
public MyConfig myConfig() throws IOException {
if (no config file) throw new NoConfigFileException();
}
}
我有一个测试是否构建了 Spring 应用程序的上下文:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@TestPropertySource(locations="classpath:file_with_existing_config_file_path.properties")
public class MyApplicationTest {
@Test
public void contextLoads() {
}
}
此测试失败 - 正如预期的那样(因为 myConfig
方法抛出 NoConfigFileException
)。不幸的是我不能 "turn the light to green" 使用注释 @Test(expected = NoConfigFileException.class)
.
如果不是在我得到的唯一一种测试方法中,我应该在哪里期待异常?
编写自动化测试的黄金法则是 -> 每个测试方法覆盖一个测试用例(除非您进行参数化测试)。在我看来,你正在考虑打破那个规则。
考虑单独测试 class(您不指定属性文件),它仅测试这方面或您的逻辑。这样你就可以使用 @Test(expected = NoConfigFileException.class)
.
顺便说一句,我建议查看 Spring 引导功能 @ConfigurationProperties。您可以对您的属性使用 Java EE 验证(例如 @NotNull)。
如果没有配置文件加载到 Spring 上下文中,您可以强制应用程序查找文件并尽早失败。