@SpringBootTest
@RunWith(SpringRunner.class)
@SpringBootConfiguration
public class SpringBootJunitTest {
@Autowired
HostOperationService hostOperationServiceImpl;
@Test
public void test1() {
System.out.println("this is test");
}
}
当以上代码启动将会报如下错误:
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'SpringBootJunitTest': Unsatisfied dependency expressed through field 'hostOperationServiceImpl'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.host.service.HostOperationService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:643)
修改注解为:
@SpringBootTest(classes = ApplicationStart.class)
这个ApplicationStart.class就是对应你项目SpringBoot Main函数启动的这个类,而不是Application默认类!
备注:如果当前项目集成了websocket Junit 测试前必须先注释不然会报错