如何使用具有多个其他依赖项(服务和repos)的Mocked存储库来测试服务?

时间:2017-06-23 10:58:26

标签: java spring spring-boot junit mockito

我正在使用Mockito测试我的SpringBoot服务。

问题在于,我测试的某些服务与其他服务和存储库存在多种依赖关系,这使得难以在更深层次的服务上执行测试。

例如:

班级" TestService"包含以下方法:

public Test addTagToTest(Long id, Long tagId) {
    Tag tag = tagService.getById(tagId);
    Test test = getById(id);

    test.addTag(tag);
    return update(test);
}

此类与" TagService"有依赖关系。 注意:每个服务都有自己的存储库。

这是TestService使用的服务类:

@Service
public class TagService extends GenericAbstractService<Tag, TagRepo> {
    public Tag getTagByName(String tagName){

在我的包含@Test方法的JUnit测试类中,我有这样的东西:

@Autowired
private TestService testService;

@Mock
private TestRepo repository;

现在的问题是如何测试我的TestService哪个依赖哪个依赖?必须嘲笑所有存储库。

1 个答案:

答案 0 :(得分:4)

你不必嘲笑所有这些。模拟一层类就足够了。 测试服务正在调用TagService.getById()。在这种情况下,TagService正在对存储库进行方法调用并获取结果。我们可以模拟TagService.getById()。具体与Mockito,

@Mock
private TagService tagService;

@Test
public void yourTest() {
    doReturn(<tag object you want>)
            .when(tagService).getById();
}

在这种情况下,实际上并没有调用TagService.getById。它直接返回您想要返回的内容。因此,您不必担心在TagService中自动装配的存储库。希望这会有所帮助。