问:Mockito-使用@Mock和@Autowired

时间:2018-08-31 16:17:21

标签: java junit mockito

我想使用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.classMockito,如下所示。

@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 个答案:

答案 0 :(得分:1)

您要注入依赖关系并形成一些功能,然后使用@Spy。 您无需加载Spring Container并使用@Autowired

@Spy
private Hello2Service hello2Service=new Hello2Service();

您可以阅读有关模拟与间谍的更多详细信息;

https://dzone.com/articles/mockito-mock-vs-spy-in-spring-boot-tests

答案 1 :(得分:1)

您可以使用Spy更改真实对象,而不是模拟。 测试代码将是这样;

@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."));
    }
}