Q:Mockito - Using @Mock and @Autowired

3

我想使用 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.classHello2Service.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."));
    }
}
2个回答

2

谢谢你的回答。它有效。 如果Hello2Service有一个jpa仓库,我该如何实例化Hello2Service?像这样public class public class Hello2Service { @Autowired HelloRepository helloRepository;...}@Repository interface HelloRepository extends JpaRepository... - fanfanta

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接