我在Sping Boot 应用程序中为Jpastreader编写JUnit测试时遇到问题。
下面是显示的服务
@Service
@RequiredArgsConstructor
public class PersonService {
private final JPAStreamer jpaStreamer;
public List<Person> findByAgeForJpaStreamer(Integer age) {
return jpaStreamer.stream(Person.class).
filter(Person$.age.equal(age)).
collect(Collectors.toList());
}
}
字符串
下面是BaseServiceTest
@ExtendWith(MockitoExtension.class)
@ActiveProfiles(value = "test")
public abstract class BaseServiceTest {
}
型
下面是PersonServiceTest
class PersonServiceTest extends BaseServiceTest {
@InjectMocks
private PersonService personService;
@Mock
private JPAStreamer jpaStreamer;
private List<Person> personList;
@BeforeEach
public void setup() {
personList = Arrays.asList(
Person.builder().id(1L).firstName("John").lastName("Doe").age(33).birthday(LocalDate.of(1990, 5, 15)).build(),
Person.builder().id(2L).firstName("Jane").lastName("Smith").age(27).birthday(LocalDate.of(1996, 9, 20)).build(),
Person.builder().id(3L).firstName("David").lastName("Johnson").age(32).birthday(LocalDate.of(1991, 9, 20)).build()
);
}
@Test
public void testJpaStreamerFindByAge() {
// given
Stream<Person> personStreamMock = personList.stream();
Stream<Person> filteredStreamMock = personStreamMock
.filter(person -> person.getAge() == 32);
List<Person> collectedListMock = filteredStreamMock.collect(Collectors.toList());
// whwn
Mockito.when(jpaStreamer.stream(Person.class)).thenReturn(personStreamMock);
Mockito.when(personStreamMock.filter(Mockito.any())).thenReturn(filteredStreamMock);
Mockito.when(filteredStreamMock.collect(Collectors.toList())).thenReturn(collectedListMock);
// then
List<Person> actualPersons = personService.findByAgeForJpaStreamer(32);
// Assert the result
assertEquals(collectedListMock, actualPersons);
assertEquals(collectedListMock.size(), actualPersons.size());
// Assert each person's properties
for (int i = 0; i < collectedListMock.size(); i++) {
assertEquals(collectedListMock.get(i).getId(), actualPersons.get(i).getId());
assertEquals(collectedListMock.get(i).getFirstName(), actualPersons.get(i).getFirstName());
assertEquals(collectedListMock.get(i).getLastName(), actualPersons.get(i).getLastName());
assertEquals(collectedListMock.get(i).getAge(), actualPersons.get(i).getAge());
assertEquals(collectedListMock.get(i).getBirthday(), actualPersons.get(i).getBirthday());
}
// Verify the JPAStreamer method calls
Mockito.verify(jpaStreamer, Mockito.times(1)).stream(Person.class);
Mockito.verify(personStreamMock, Mockito.times(1)).filter(Mockito.any());
Mockito.verify(filteredStreamMock, Mockito.times(1)).collect(Collectors.toList());
}
型
我在那一行有问题
Mockito.when(personStreamMock.filter(Mockito.any())).thenReturn(filteredStreamMock);
型
它抛出空指针异常。
我该怎么解决?
1条答案
按热度按时间ecfsfe2w1#
在项目中定义jpastreamer配置后,问题消失了。
字符串