【问题标题】:How can I access Objects within a void method while unit testing?单元测试时如何在 void 方法中访问对象?
【发布时间】:2020-03-30 23:10:01
【问题描述】:

我正在对 Spring Boot 服务方法进行单元测试。我有一个没有参数的 void 方法。它查询一个数据库并获取一个列表。我可以嘲笑和断言。然后它遍历列表并根据某些条件更改对象字段。我怎样才能检查该列表的内容,以便对它们进行断言?

@Transactional
public void someMethod() {
    List<Person> myList = repository.findAllByAge(0);
    myList.forEach(person -> person.setAge(18));
}

如何在 myList 上断言以检查 myList 中年龄为 0 的每个人都设置为 18 岁?我目前在我的测试课上有这个......

@Test
public void someMethod_withSuccess() {
    List<Person> testList = new ArrayList<>();
    testList.add(toPersonEntity(createPersonDto().setAge(0)));
    when(mockRepo.findAllByAge(0)).thenReturn(testList);

    mockService.someMethod();
}

【问题讨论】:

  • 您能否分享一些代码,以便我们更好地了解您拥有什么以及您正在尝试做什么?
  • 当您模拟该方法时,您会传递您期望的结果列表。因此,请在该结果列表中声明您期望的更改。
  • 使用 ArgumentCaptor 你可以做到这一点,发布你的代码可以帮助回答。

标签: java unit-testing mockito void


【解决方案1】:

就这么简单

testList.forEach(person -> assertThat("person "+testList.indexOf(person),person.getAge(),equalTo(28)));

【讨论】:

    【解决方案2】:

    您可以通过Reflection API调用该方法。

    顺便说一句,如果你需要测试这个方法,它可能必须重新设计为公开或根本不测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-23
      • 2014-05-10
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多