测试 Spring Boot 库模块

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 一样加载。

Den*_*Ich 6

我切换到 JUnit 5 并使它有点工作......所以如果你想测试数据库的东西:

@DataMongoTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
class BasicMongoTest { ... }
Run Code Online (Sandbox Code Playgroud)
  • 允许您自动装配所有存储库和 mongo 模板
  • 使用 aplicaton.yml 配置进行初始化
  • 不初始化或配置拦截器

如果您的类路径中有一个类,则完整的应用程序上下文测试@SpringBootApplication(可以是测试上下文中的空测试 main)

@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class FullContextTest { ... }
Run Code Online (Sandbox Code Playgroud)
  • 使用所有配置和 bean 初始化完整上下文
  • 如果没有必要,就不应该这样做,因为它会加载所有应用程序上下文,并且有点违背了单元测试仅激活所需内容的目的。

仅测试特定组件和配置:

@SpringBootTest(classes = {Config1.class, Component1.class})
@EnableConfigurationProperties
@ExtendWith(SpringExtension.class)
@ActiveProfiles({"default", "test"})
public class SpecificComponentsTest { ... }
Run Code Online (Sandbox Code Playgroud)
  • 仅使用 Config1 和 Component1 类初始化上下文。Component1 和 Config1 中的所有 bean 都可以自动装配。

  • 请注意,使用“@SpringBootTest”时,“@ExtendWith(SpringExtension.class)”是多余的 (4认同)