Den*_*Ich 8 java spring automated-tests unit-testing spring-boot
我有一个多模块项目,其中并非每个模块实际上都是应用程序,但其中很多都是库。这些库正在完成主要工作,我想在它们的实现位置测试它们。库的当前依赖项:
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Run Code Online (Sandbox Code Playgroud)
在主要源代码中是一个带有@Configuration单个 bean 的类:
@Bean public String testString() { return "A Test String"; }
Run Code Online (Sandbox Code Playgroud)
我有2个测试班:
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"default", "test"})
public class Test1 {
@Test
public void conextLoaded() {
}
}
Run Code Online (Sandbox Code Playgroud)
-
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles({"default", "test"})
public class Test2 {
@Autowired
private String testString;
@Test
public void conextLoaded() {
}
}
Run Code Online (Sandbox Code Playgroud)
第一次测试有效。第二个没有。该项目中没有@SpringBootApplication任何地方,因此在与测试相同的包中我添加了测试配置:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.to.config")
public class LibTestConfiguration {
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用。对于 的类也是如此@Service。它们不在上下文中。我怎样才能让它像一个普通的 Spring boot 应用程序一样运行,而不需要它真正成为一个应用程序并从我需要的配置文件中加载配置和上下文?默认配置文件和测试配置文件共享它们的大部分属性(目前),我希望它们像启动 tomcat 一样加载。
我切换到 JUnit 5 并使它有点工作......所以如果你想测试数据库的东西:
@DataMongoTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
class BasicMongoTest { ... }
Run Code Online (Sandbox Code Playgroud)
如果您的类路径中有一个类,则完整的应用程序上下文测试@SpringBootApplication(可以是测试上下文中的空测试 main)
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class FullContextTest { ... }
Run Code Online (Sandbox Code Playgroud)
仅测试特定组件和配置:
@SpringBootTest(classes = {Config1.class, Component1.class})
@EnableConfigurationProperties
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class SpecificComponentsTest { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8029 次 |
| 最近记录: |