我想模拟我的存储库上提供的查询,如下所示:
@Test
public void GetByEmailSuccessful() {
// setup mocks
Mockito.when(this.personRepo.findAll()
.stream()
.filter(p -> (p.getEmail().equals(Mockito.any(String.class))))
.findFirst()
.get())
.thenReturn(this.personOut);
Mockito.when(this.communityUserRepo.findOne(this.communityUserId))
.thenReturn(this.communityUserOut);
...
我的@Before方法如下所示:
@Before
public void initializeMocks() throws Exception {
// prepare test data.
this.PrepareTestData();
// init mocked repos.
this.personRepo = Mockito.mock(IPersonRepository.class);
this.communityUserRepo = Mockito.mock(ICommunityUserRepository.class);
this.userProfileRepo = Mockito.mock(IUserProfileRepository.class);
}
可悲的是,当我运行测试时,我收到错误:
java.util.NoSuchElementException: No value present
当我双击错误时,它指向第一个lambda的.get()方法.
有没有人成功嘲笑过一个lambda表达式并知道如何解决我的问题?
解决方法:
没有必要嘲笑这么深的电话.只需模拟personRepo.findAll()并让Streaming API正常工作:
Person person1 = ...
Person person2 = ...
Person person3 = ...
List<Person> people = Arrays.asList(person1, person2, ...);
when(personRepo.findAll()).thenReturn(people);
而不是
.filter(p – >(p.getEmail().equals(Mockito.any(String.class))))
只需在Person对象上设置/模拟电子邮件即可获得预期值.
或者,考虑实现PersonRepo.findByEmail.