【问题标题】:@DataJpaTest - loads configuration from @SpringBootApplication class@DataJpaTest - 从 @SpringBootApplication 类加载配置
【发布时间】:2021-10-19 17:02:06
【问题描述】:

我有点困惑,基于这个documentation,我应该只放这个注释@DataJpaTest,它会将我的应用程序上下文配置为仅用于JPA存储库,也用于内存数据库。现在问题出在我的应用程序中,我有一个带有 @SpringBootApplication 注释的 Main 类,它正在从那里加载 Web 拦截器的其余配置以及许多其他内容。实际上它也在尝试加载 bootstrap.properties 文件。

据我了解,它不应该使用这种配置。

下面是我的测试代码和主类。

@OpenAPIDefinition(info = @Info(title = "Test API", version = "0.1.10-SNAPSHOT", description = "Test API", contact = @Contact(name = "My Team", email = "sample@mycompany.com")), servers = {
        @Server(description = "Current Stage Server url", url = "https://mycompany.com/testapics"),
        @Server(description = "Stable Stage Server url", url = "https://mycompany.com/testapi") })
@SpringBootApplication(scanBasePackages = { "com.mycompany.utility", "com.mycompany.sample.users",
        "com.mycompany.sample.utility", "com.mycompany.another.sample.interceptor",
        "com.mycompany.sample.security.vulnerableinput", "com.mycompany.sample.security.nocache.filter",
        "com.mycompany.sample.security.common", "com.mycompany.sample.security.csrf",
        "com.mycompany.sample.security.nocache" })
@EnableCaching
@EnableAsync
public class SampleApiApplication implements WebMvcConfigurer {

主类中有一堆其他的 bean 配置。 (为了清楚起见,省略了这些)。

下面是我的测试课。

@DataJpaTest
public class UsersRepositoryTest {

    @Autowired
    private UsersRepository usersRepository;

    @Test
    public void test_usersRepository_findByEmplId() {
        List<User> users = getUsersData();
        UsersRepository.saveAll(users);
        for (User user : users) {
            Assert.assertTrue(user.getId() != null);
        }
    }

    private List<User> getUsersData() {
        List<User> userList = new ArrayList<>();
        User user = new User();
        user.setEmpId("XYZ_001");
        user.setUserUUID(UUID.randomUUID().toString());
        userList.add(user);
        return userList;
    }

}

【问题讨论】:

    标签: java spring spring-boot unit-testing spring-data-jpa


    【解决方案1】:

    根据Spring Boot Reference

    如果您使用test annotation to test a more specific slice of your application,则应避免在main method’s application class 上添加特定于特定区域的配置设置。

    @SpringBootApplication 的底层组件扫描配置定义了排除过滤器,用于确保切片按预期工作。如果您在 @SpringBootApplication-annotated 类上使用显式的 @ComponentScan 指令,请注意这些过滤器将被禁用。如果你使用切片,你应该重新定义它们。

    因此,在您的情况下,请考虑将 @EnableCaching@EnableAsync 等注释移动到单独的类中。

    【讨论】:

      猜你喜欢
      • 2018-10-11
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多