Chr*_*oph 4 java lambda junit unit-testing mockito
我想模拟我的存储库上提供的查询,如下所示:
@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);
...
Run Code Online (Sandbox Code Playgroud)
我的@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);
}
Run Code Online (Sandbox Code Playgroud)
可悲的是,当我运行测试时,我收到错误:
java.util.NoSuchElementException:没有值存在
当我双击错误时,它指向.get()第一个lambda 的方法.
有没有人成功嘲笑过一个lambda表达式并知道如何解决我的问题?
没有必要嘲笑这么深的电话.只需模拟personRepo.findAll()并让Streaming API正常工作:
Person person1 = ...
Person person2 = ...
Person person3 = ...
List<Person> people = Arrays.asList(person1, person2, ...);
when(personRepo.findAll()).thenReturn(people);
Run Code Online (Sandbox Code Playgroud)
而不是
.filter(p -> (p.getEmail().equals(Mockito.any(String.class))))
只是设置/模拟email你的Person对象是预期值.
或者,考虑实施PersonRepo.findByEmail.