【问题标题】:Spring Boot problem with JUnit execution testJUnit执行测试的Spring Boot问题
【发布时间】:2019-09-01 19:59:20
【问题描述】:

我在运行 Junit 测试时遇到问题,我有错误:

java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
    at org.springframework.util.Assert.state(Assert.java:73)

我怎么看,Spring Boot 找不到我的测试类。我有多个 Maven 模块,在我的 A 模块中我有 SpringBootApplication 类和控制器,在模块 B 我有我的服务模块,我写了我的测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestClass{

    @Autowired
    private ImplDatabase serviceDatabase;

    @MockBean
    private Repository repository;

    @Test
    public void saveMethode() {
        Model model= new Model ();

        event.setCreated(LocalDateTime.now());
        model.setMessage("sdsd");
        model.setCategory("Somi");

        when(repository.save(model)).thenReturn(model);
        assertEquals(model, serviceDatabase.saveTest(model));
    }

}

我有C 模块,其中存储了我的Repository

依赖的层次是:我在A 模块中对BC 有依赖,在B 模块中我对C 有依赖。

【问题讨论】:

    标签: java maven spring-boot mockito junit4


    【解决方案1】:

    在模块B你可以创建

    @ComponentScan({"com.mycompany.myapp.moduleB",
                    "com.mycompany.myapp.moduleB.subpackage1",
                    "com.mycompany.myapp.moduleB.subpackage1.subsubpackage1a",
                    "com.mycompany.myapp.moduleB.subpackage2"
                     /*add here all required packages to scan for B's components and services*/ })
    public class BConfig {}
    

    然后将模块 B 中的 Junit 测试标记为 @SpringBootTest(classes = BConfig.class)

    注意,BConfig 不必在主源中,将其放在测试源中

    【讨论】:

      【解决方案2】:

      错误信息提示你需要指定你的应用上下文类 b/c spring 找不到它:

      @RunWith(SpringRunner.class)
      // Application is the class annotated with @SpringBootApplication
      @SpringBootTest(classes = {Application.class}) 
      public class TestClass {
          .....
      }
      

      【讨论】:

      • 好的,但是我有一个问题,我无法为Application.class 导入包,我的B 无法识别我的A 模块。我怎么说我的测试类在我的B 模块中。
      • 如果你想在模块 B 中对你的服务进行单元测试,那么你不应该依赖于模块 A,你应该模拟模块 B 外部的任何依赖关系。如果你想使用以下组件执行集成测试模块 A 那么您应该在模块 A 中编写测试,而不是在模块 B 中。希望对您有所帮助。
      猜你喜欢
      • 2023-03-03
      • 2019-08-23
      • 2019-10-26
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      相关资源
      最近更新 更多