首页 > 解决方案 > @MockBean 和 @Autowired 在一个测试类中的相同服务

问题描述

是否有可能以某种方式拥有相同的测试类@MockBean@Autowired相同的服务?

换句话说,我@MockBean只想为一个测试提供服务,而对于同一类的其他测试,我需要它作为@Autowired.

标签: javaspringjunitmockitospring-boot-test

解决方案


@MockBean这取决于和之间的差异@Autowired

@Autowired

只在SpringContextbean 中查找该类型的 bean。这意味着如果您需要“自动装配”它,您将需要创建该 bean

@MockBean

完全符合您对名称的期望,它创建了服务的“模拟”,并将其作为 bean 注入。

所以这

class MyTest {
   @MockBean
   MyService myService;
}

相当于这个

@Import(MyTest.Config.class)
class MyTest {

   @Autowired
   MyService myService;

   @TestConfiguration
   static class Config {

      @Bean
      MyService myService() {
         return Mockito.mock(MyService.class);
      }
   }
}

因此,如果您需要在其他测试中使用不同类型的 bean,则需要在带注释的类MyService中创建 bean@TestConfiguration

@Import(MyTest.Config.class)
class MyTest {

   @Autowired
   MyService myService;

   @TestConfiguration
   static class Config {

      @Bean
      MyService myService() {
         return new MyServiceImpl();
      }
   }
}

或者,在一个带有注释的类中@Configuration

@Import(MyConfig.class)
class MyTest {
   @Autowired
   MyService myService;
}

@Configuration
public class MyConfig {
   @Bean
   MyService myService() {
      return new MyServiceImpl();
   }
}

推荐阅读