Java JUnit执行测试的Spring启动问题
我在运行Junit测试时遇到问题,出现错误:Java JUnit执行测试的Spring启动问题,java,maven,spring-boot,mockito,junit4,Java,Maven,Spring Boot,Mockito,Junit4,我在运行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) 我怎么看
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
模块,其中存储了我的存储库
依赖关系的层次结构是:我在
A
模块中对B
和C
有依赖关系,在B
模块中,我对C
有依赖关系。错误消息建议您需要指定应用程序上下文类B/C spring找不到它:
@RunWith(SpringRunner.class)
// Application is the class annotated with @SpringBootApplication
@SpringBootTest(classes = {Application.class})
public class TestClass {
.....
}
在模块
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 {}
然后用@SpringBootTest(classes=BConfig.class)
注意,
BConfig
不必在主要源代码中,将其放在测试源代码中可以,但我有一个问题,我无法为应用程序导入包。类
,我的B
无法识别我的a
模块。我是如何说我的测试类在我的B
模块中的。如果你想在模块B中单元测试你的服务,那么你不应该对模块a有依赖关系,你应该模拟模块B外部的任何依赖关系。如果你想对模块a的组件执行集成测试,那么你应该在模块a中编写测试,不在模块B中。希望这有帮助。