猿问

Q:Mockito - 使用@Mock 和@Autowired

我想测试一个服务类,它有两个其他服务类,如下所示使用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.";

    }

}    

我知道如何嘲笑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."));

    }

}


慕田峪7331174
浏览 726回答 2
2回答

冉冉说

您可以使用 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."));    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答