本文介绍了使用Mockito 2.0.7模拟lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟我的存储库中提供的查询,如下所示:

I want to mock a query provided on my repository like this:

@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);
}

遗憾的是,当我运行测试时收到错误:

Sadly when I run the test I receive the error:

何时我双击它指向第一个lambda的 .get()方法的错误。

When I double-click the error it points at the .get() method of the first lambda.

有任何错误你成功地模拟了一个lambda表达式并知道如何解决我的问题吗?

Have any of you successfully mocked a lambda expression and know how I can solve my problem?

推荐答案

没有必要模拟这样的深度调用。只需模拟 personRepo.findAll()并让Streaming API正常工作:

There's no need to mock such deep calls. Simply mock personRepo.findAll() and let the Streaming API work as normal:

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 对象上设置/模拟电子邮件作为预期值。

just set/mock email on your Person objects to be the expected value.

或者,考虑实施 PersonRepo.findByEmail

这篇关于使用Mockito 2.0.7模拟lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:26