带有忽略案例查找器方法的 JPA 存储库的 Mockito 'when'



我正在尝试模拟不区分大小写的用户存储库。。。mockito返回一个不应该返回的对象。。。

Pattern adminPattern = Pattern.compile(Pattern.quote("admin"), Pattern.CASE_INSENSITIVE);
Pattern admin2Pattern = Pattern.compile(Pattern.quote("admin2"), Pattern.CASE_INSENSITIVE);
Mockito.when(userRepo.findByUserNameIgnoreCase(Mockito.matches(adminPattern))).thenReturn(user1);
Mockito.when(userRepo.findByUserNameIgnoreCase(Mockito.matches(admin2Pattern))).thenReturn(user2);
Assert.isTrue(adminPattern.matcher("admin").matches(), "admin should match");
Assert.isTrue(adminPattern.matcher("adMIN").matches(), "adMIN should match");
Assert.isTrue(admin2Pattern.matcher("admin2").matches(), "admin2 should  match");
Assert.isTrue(admin2Pattern.matcher("adMIN2").matches(), "adMIN2 should  match");
Assert.isTrue(!adminPattern.matcher("admin3").matches(), "admin3 should not match");
Assert.isTrue(!admin2Pattern.matcher("adMIN").matches(), "adMIN should not match");
Assert.isTrue(!admin2Pattern.matcher("adMIN3").matches(), "adMIN3 should not match");
Assert.isTrue(userRepo.findByUserNameIgnoreCase("admin").equals(user1), "Admin must be found");
Assert.isTrue(userRepo.findByUserNameIgnoreCase("adMIN").equals(user1), "Admin must be found");
Assert.isNull(userRepo.findByUserNameIgnoreCase("anything"), "anything must not be found");
Assert.isNull(userRepo.findByUserNameIgnoreCase("admin3"), "Admin3 must not be found");

最后一行出错了。。。Mockito返回user1而不是什么都不返回。在我看来,"matches"实际上是一个"startsWith",这让我有点惊讶。。。或者我的正则表达式模式匹配器错误。。。或者我错过了其他一些非常明显的东西(对其他人来说:-(

非常感谢你的一些想法!

如果您查看org.mockito.internal.matchers.Matches类,您会注意到,它在regex模式匹配器上调用find,而不是matches

@Override
public boolean matches(Object actual) {
return (actual instanceof String) && pattern.matcher((String) actual).find();
}

区别在于:

  • find查找输入字符串中出现的模式
  • CCD_ 5尝试将整个输入与模式相匹配

要强制匹配整个输入,您可以稍微修改您的模式:"^admin$"

最新更新