我想測試一個服務類,它有兩個其他服務類,如下所示使用Mockito.@Servicepublic class GreetingService { private final Hello1Service hello1Service; private final Hello2Service hello2Service; @Autowired public GreetingService(Hello1Service hello1Service, Hello2Service hello2Service) { this.hello1Service = hello1Service; this.hello2Service = hello2Service; } public String greet(int i) { return hello1Service.hello(i) + " " + hello2Service.hello(i); }}@Servicepublic class Hello1Service { public String hello(int i) { if (i == 0) { return "Hello1."; } return "Hello1 Hello1."; }}@Servicepublic class Hello2Service { public String hello(int i) { if (i == 0) { return "Hello2."; } return "Hello2 Hello2."; }} 我知道如何嘲笑Hello1Service.class,并Hello2Service.class用Mockito類似如下。@RunWith(MockitoJUnitRunner.class)public class GreetingServiceTest { @InjectMocks private GreetingService greetingService; @Mock private Hello1Service hello1Service; @Mock private Hello2Service hello2Service; @Test public void test() { when(hello1Service.hello(anyInt())).thenReturn("Mock Hello1."); when(hello2Service.hello(anyInt())).thenReturn("Mock Hello2."); assertThat(greetingService.greet(0), is("Mock Hello1. Mock Hello2.")); }}我想模擬Hello1Service.class和注入Hello2Service.class使用@Autowired如下所示。我厭倦了使用,@SpringBootTest但它沒有用。有沒有更好的辦法?@RunWith(MockitoJUnitRunner.class)public class GreetingServiceTest { @InjectMocks private GreetingService greetingService; @Mock private Hello1Service hello1Service; @Autowired private Hello2Service hello2Service; @Test public void test() { when(hello1Service.hello(anyInt())).thenReturn("Mock Hello1."); assertThat(greetingService.greet(0), is("Mock Hello1. Hello2.")); }}
Q:Mockito - 使用@Mock 和@Autowired
慕田峪7331174
2021-08-25 09:49:43