Spring JUnit 执行测试的引导问题
Spring Boot problem with JUnit execution test
我遇到了 运行 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开机找不到我的测试Class。我有多个 Maven 模块,在我的 A
模块中,我有 SpringBootApplication
class 和控制器,在模块 B
中,我有我的服务模块,我写了我的测试 Class:
@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
模块中依赖 B
和 C
,在 B
模块中我依赖 C
.
错误消息提示您需要指定您的应用程序上下文class 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 {}
然后在模块B中用@SpringBootTest(classes = BConfig.class)
标记Junit测试
注意,BConfig
不必在主源中,将其放在测试源中
我遇到了 运行 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开机找不到我的测试Class。我有多个 Maven 模块,在我的 A
模块中,我有 SpringBootApplication
class 和控制器,在模块 B
中,我有我的服务模块,我写了我的测试 Class:
@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
模块中依赖 B
和 C
,在 B
模块中我依赖 C
.
错误消息提示您需要指定您的应用程序上下文class 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 {}
然后在模块B中用@SpringBootTest(classes = BConfig.class)
注意,BConfig
不必在主源中,将其放在测试源中