Java 使用mockito2.0.7模拟lambda表达式
我想模拟存储库中提供的查询,如下所示:Java 使用mockito2.0.7模拟lambda表达式,java,unit-testing,junit,lambda,mockito,Java,Unit Testing,Junit,Lambda,Mockito,我想模拟存储库中提供的查询,如下所示: @Test public void GetByEmailSuccessful() { // setup mocks Mockito.when(this.personRepo.findAll() .stream() .filter(p -> (p.getEmail().equals(Mockito.any(String.class)))) .findFirst()
@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
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);
}
我的@Before
方法如下所示:
@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
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:不存在值
当我双击错误时,它指向第一个lambda的.get()
方法
你们有谁成功地模拟了lambda表达式,知道我如何解决我的问题吗?没有必要模拟这种深度调用。只需模拟personRepo.findAll(),让流式API正常工作:
Person person1 = ...
Person person2 = ...
Person person3 = ...
List<Person> people = Arrays.asList(person1, person2, ...);
when(personRepo.findAll()).thenReturn(people);
Person-person1=。。。
Person person2=。。。
个人3=。。。
List people=Arrays.asList(person1,person2,…);
when(personRepo.findAll())。然后返回(people);
而不是
.filter(p->(p.getEmail().equals(Mockito.any(String.class)))
只需将Person
对象上的/mockemail
设置为预期值
可选的,考虑执行<代码> PrimePo.FunByEdmail < /C> > < /P> < P> >两件事:
Mockito.when(this.personRepo.findAll()
.stream()
.filter(p -> (p.getEmail().equals(Mockito.any(String.class))))
.findFirst()
.get())
.thenReturn(this.personOut);
首先,您尝试模拟由五个不同方法调用组成的链。莫基托处理得不太好;虽然(如果放在personRepo上)将在适用的情况下保存并返回存根对象,但每次调用when
时,本身只会存根一个调用
其次,Mockito匹配器不够灵活,无法深入处理呼叫;当时对的调用应该只包含一个没有链接的方法调用,而对类似any
的Mockito匹配器的调用应该包含。按照您的方式,您正在创建一个谓词p->(p.getEmail().equals(null))
,并在堆栈上留下一个匹配器,以便稍后进行分解
使用来解决此问题,并注意在将来的问题中正确地使用stub和matcher。我可能错了,但我认为您必须首先为personRepo.findAll()指定一个返回值,然后为所有方法调用指定一个返回值。
我感觉不好,您希望测试mockito而不是测试代码。getByEmail()的代码是什么?它应该做什么?