【问题标题】:How to test a Service with a Mocked repository that has multiple other dependencies (services and repos)?如何使用具有多个其他依赖项(服务和存储库)的 Mocked 存储库测试服务?
【发布时间】:2017-06-23 10:58:25
【问题描述】:

我正在使用 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 有依赖关系有依赖关系?必须模拟所有存储库。

【问题讨论】:

标签: java spring spring-boot junit mockito


【解决方案1】:

您不必模拟所有这些。模拟一层类就足够了。 测试服务正在调用 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 中自动装配的存储库。希望这会有所帮助。

【讨论】:

  • 您还必须记住在您的类中添加 @RunWith(MockitoJUnitRunner.class) 注释,或者添加带有 @Before 注释的方法,其中包括 MockitoAnnotations.initMocks(this);
  • 是的。我试图解释这个问题而不是实际的代码 sn-p。
  • @476rick,如果这个答案对你有用,你能接受吗?或者,如果您期待其他内容,请更新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 2020-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多