在单元测试中如何在void方法内访问对象?

问题描述 投票:0回答:2

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

@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();
}
java unit-testing mockito void
2个回答
0
投票

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

btw,如果您需要测试此方法,则可能必须重新分配它以将其公开或完全不进行测试。


0
投票

就这么简单

testList.forEach(person -> assertThat("person "+testList.indexOf(person),person.getAge(),equalTo(28)));
© www.soinside.com 2019 - 2024. All rights reserved.