我想使用 Mockito
测试一个服务类,该类包含如下两个其他服务类。
@Service
public 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);
}
}
@Service
public class Hello1Service {
public String hello(int i) {
if (i == 0) {
return "Hello1.";
}
return "Hello1 Hello1.";
}
}
@Service
public class Hello2Service {
public String hello(int i) {
if (i == 0) {
return "Hello2.";
}
return "Hello2 Hello2.";
}
}
我知道如何使用 Mockito
来模拟 Hello1Service.class
和 Hello2Service.class
,像下面这样。
@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
并使用@Autowired
注入Hello2Service.class
,如下所示。
我尝试使用@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."));
}
}
public class public class Hello2Service { @Autowired HelloRepository helloRepository;...}
@Repository interface HelloRepository extends JpaRepository...
- fanfanta