首页 > 解决方案 > SpringBoot Junit5在重命名包含@SpringBootApplication注释的类的包时失败

问题描述

将 @SpringBootApplication 移动到不同的包时,我正在努力使用 JUnit 5。

我已经使用 Maven 和 Eclipse 设置了一个新的 SpringBoot 项目(2.2.1.RELEASE)(必须从“Eclipse Photon”升级它以支持 SpringBoot-Release

我的包布局如下所示:

/src/main/java
   com.package.sample.appl1
     StartSamples.java
   com.package.sample.appl1.start
   com.package.sample.appl1.dbaccess
   com.package.sample.appl1.run
   com.package.sample.appl1.utils
   com.package.sample.appl2.run
   com.package.sample.appl2.run

/src/test/java
   com.package.sample.appl1.dbaccess
     SimpleTest.java

持有@SpringBootApplication 的类是:

@ComponentScan({
    "com.package.sample"
    })
@SpringBootApplication
public class StartSamples {
   public static void main(String[] args) {
        System.out.println("Start");
        try {
            SpringApplication.run(StartSamples.class, args);
        } catch (Exception e) {
            LOGGER.error("", e);
            System.exit(-1);
        }
    }

测试是这样的:

import static org.junit.Assert.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit.jupiter.SpringExtension;

/**
 * Test the Query-statements and the DAO methods
 * 
 * @author U005078
 *
 */
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ComponentScan({
    "com.package.sample"})
@EnableAutoConfiguration
public class SimpleTest {

    @SuppressWarnings("unused")
    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleTest.class);

    @Test
    @DisplayName("SimpleTest")
    public void testTotalRows() {

有了这个配置,一切都很好,“StartSamples”按预期工作并且aqlso SimpleTest。

但是当将“StartSamples”移动到不同的包时(例如“com.package.sample.start”对我来说更有意义 - “StartSamples”仍然可以,但“SimpleTest”不会失败也不会成功 - 测试似乎没有被执行. 我看到一条消息:类路径资源[com/package/sapmle/appl1/dbaccess/SimpleTest-context.xml] 不存在类路径资源[com/package/sapmle/appl1/dbaccess/SimpleTestContext.groovy] 不存在.SimpleTest]:SimpleTest 不声明任何使用@Configuration 注解的静态、非私有、非最终、嵌套类。

我还发现:使用 SpringBootContextLoader 没有为测试类 [com.package.sample.appl1.dbaccess.SimpleTest] 找到 @ContextConfiguration 和 @ContextHierarchy

所以我将@ContextConfiguration 定义为“SimpleTest”,然后它就起作用了。但我完全不明白为什么 @SpringBootApplication 的移动确实改变了这种行为。

再次尝试设置这个项目时,我最终得到“没有使用测试运行器'JUnit 5'找到测试”,也找不到任何原因。我用当前的方法重新开始并到达这里。并且不知道是什么给了我错误 - 对于任何一个问题。

任何解释都将不胜感激。我现在尝试了很多小时在互联网上找到一些东西——但我只找到了“试试这个”、“试试那个”这样的建议,但对理解没有帮助。所以任何帮助表示赞赏。

标签: springspring-bootjunitjunit-jupiter

解决方案


定义您的 SpringBoot Main 类,如下所示

@SpringBootTest(classes = {StartSamples.class})
public class SimpleTest {
   ...
}

推荐阅读