为了账号安全,请及时绑定邮箱和手机立即绑定

Q:Mockito - 使用@Mock 和@Autowired

Q:Mockito - 使用@Mock 和@Autowired

慕田峪7331174 2021-08-25 09:49:43
我想测试一个服务类,它有两个其他服务类,如下所示使用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."));    }}
查看完整描述

2 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

您可以使用 Spy 更改真实对象而不是 Mock。测试代码会是这样;


@RunWith(MockitoJUnitRunner.class)

public class GreetingServiceTest {


    @InjectMocks

    private GreetingService greetingService;


    @Mock

    private Hello1Service hello1Service;


    @Spy

    private Hello2Service hello2Service;


    @Test

    public void test() {


        when(hello1Service.hello(anyInt())).thenReturn("Mock Hello1.");

        assertThat(greetingService.greet(0), is("Mock Hello1. Hello2."));

    }

}


查看完整回答
反对 回复 2021-08-25
  • 2 回答
  • 0 关注
  • 725 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信