一个测试类中同一服务的 @MockBean 和 @Autowired

Mik*_*yer 11 java junit spring mockito spring-boot-test

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

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

Ahm*_*yed 6

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

@Autowired

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

@MockBean

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

所以这

class MyTest {
   @MockBean
   MyService myService;
}
Run Code Online (Sandbox Code Playgroud)

相当于这个

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

   @Autowired
   MyService myService;

   @TestConfiguration
   static class Config {

      @Bean
      MyService myService() {
         return Mockito.mock(MyService.class);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

   @Autowired
   MyService myService;

   @TestConfiguration
   static class Config {

      @Bean
      MyService myService() {
         return new MyServiceImpl();
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

@Configuration
public class MyConfig {
   @Bean
   MyService myService() {
      return new MyServiceImpl();
   }
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*ich 6

最好的解决方案是更改@MockBean@SpyBean。在该方法中,您将能够这样做:

科特林

    @SpyBean
    lateinit var serviceMock: Service

    @Test
    fun smallTest()
        `when`(serviceMock.doSomething())
            .thenReturn(false)

        // your test logic
    }

Run Code Online (Sandbox Code Playgroud)