Junit在springboot中测试独立的服务层

时间:2017-09-16 12:08:39

标签: java spring unit-testing spring-boot junit

我将独立服务层打包为jar maven模块。也是道层。 (基本上3个项目1个用于控制器,1个服务,1个dao)

所有配置和In [660]: data1, data2 = pd.DataFrame(data).set_index([0, 1]).unstack()[2].to_dict('r') In [661]: data1 Out[661]: {'c1': 'avg11', 'c2': 'stdev12'} In [662]: data2 Out[662]: {'c1': 'stdev21', 'c2': 'stdev22'} In [663]: pd.DataFrame(data).set_index([0, 1]).unstack()[2].to_dict('r') Out[663]: [{'c1': 'avg11', 'c2': 'stdev12'}, {'c1': 'stdev21', 'c2': 'stdev22'}] 都在控制器层中。在控制器单元测试工作正常,下面注释。

MainSpringBootApplication.java

现在我想要单元测试服务层。但面临错误。 服务层类具有注释

@SpringBootTest
@RunWith(SpringRunner.class)
@ActiveProfiles("testenv")

它会出现如下错误

Dao层的情况也是如此。 如何使用test.properties文件为此类项目结构配置弹簧以进行单元测试。 注意:我使用NO XML配置。 任何帮助表示赞赏。

@RunWith(SpringRunner.class)
@ActiveProfiles("testenv")
@PropertySource("classpath:application-testenv")

修改 建议更改后的错误跟踪

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.test.example.TestSrevice': Unsatisfied dependency expressed through field 'testService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestSrevice' 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:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:386)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.test.example.TestSrevice' 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.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 28 more

3 个答案:

答案 0 :(得分:1)

您可以使用@ContextConfiguration注释提供一些测试配置以用于单元测试。如果您需要使用@ComponentScan,我建议您在测试类中使用静态内部类进行配置。使用没有参数的@ContextConfiguration注释您的测试类将默认使用该内部类进行配置:

@RunWith(SpringRunner.class)
@ActiveProfiles("testenv")
@PropertySource("classpath:application-testenv")
@ContextConfiguration
public class MyServiceTest {

  ...

  @ComponentScan
  @Configuration
  public static class MyServiceTestConfiguration {

     @Bean
     public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
         return new PropertySourcesPlaceholderConfigurer();
     }

  }
}

我还包含了一个PropertySourcesPlaceholderConfigurer bean,因为我非常确定你还需要它来正确读取你的属性。

答案 1 :(得分:1)

根据您在下面的失败,它确认您的DAO未被创建。也许他们没有被扫描,在这种情况下你需要确保包被扫描。如果他们被扫描但DAO没有被创建,问题可能是JPA没有加载。

  

引起:   org.springframework.beans.factory.NoSuchBeanDefinitionException:没有   属于' com.test.example.TestDao'的限定bean可用:预期   至少有1个符合autowire候选资格的bean。依赖   注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

您可能需要在测试中添加以下注释: Set ObjWMI= GetObject("WInmgmts:") Set oProcess = ObjWMI.ExecQuery("Select * from win_32 Process") For each p in oProcess if p.name = "iexplorer.exe" Then p.terminate Next ,如@DataJpaTest文档中所述:

  

可以与之结合使用的注释   @RunWith(SpringRunner.class)进行典型的JPA测试。可以用的时候   测试仅关注JPA组件。使用此注释将   禁用完全自动配置,而只应用配置   与JPA测试相关。

     

默认情况下,使用@DataJpaTest注释的测试将使用嵌入式   内存数据库(替换任何显式或通常自动配置   数据源)。 @AutoConfigureTestDatabase注释可用于   覆盖这些设置。

     

如果您要加载完整的应用程序配置,但是   使用嵌入式数据库,你应该考虑@SpringBootTest的组合   使用@AutoConfigureTestDatabase而不是此注释。

答案 2 :(得分:0)

谢谢@Plog和@JC Carrillo我失踪<div class="row"> <div class="span9"> <ul class="thumbnails"> <li class="span9"> <select onchange="loadFrame(this.value,'starterVID');this.selectedIndex=0;"> <option>Choose A View</option> <option value="yahoo.com>Vid02</option> <option value="youtube.com/">Vid03</option> <option value="google.com">Vid04</option> <option value="google.com">Vid05</option> <option value="google.com">Vid06</option> <option value="google.com">Vid07</option> <option value="google.com">Vid08</option> <option value="google.com">Vid09</option> <option value="google.com">Vid10</option> </select> <div class="flex-video widescreen vimeo"> <iframe name = "starterVID" id = "starterVID" width="870" height="498" src="https://www.youtube.com/" frameborder="0" allowfullscreen> </iframe> </div> </li> </ul> </div> </div> 另外@DataJpaTest@EntityScan("com.test")这解决了问题,但我的测试仍然失败,因为它没有从中获取h2数据库的配置给定属性文件和引导程序以自行管理它。