我是JMockit的新手并且已成功使用它运行基本单元测试。但是,我在尝试模拟Spring LdapTemplate时遇到困难。问题似乎与LdapTemplate使用的LdapQuery有关。我是否也需要嘲笑这个?
JUnit测试
@RunWith(JMockit.class)
public class MyTest {
@Mocked
LdapTemplate mockLdapTemplate;
@Test
public void retrieveAccount_test() {
Account acct = new Account();
acct.setEmail("foobar@gmail.com");
acct.setUserId("userA");
final List<Account> expected = Arrays.asList(acct);
new Expectations() {
{
mockLdapTemplate.search(query().base(anyString).where(anyString)
.is("userA"), (AttributesMapper) any);
result = expected;
}
};
AccountService service = new AccountServiceImpl(mockLdapTemplate);
Account account = service.retrieveAccount("userA");
assertThat(account, is(notNullValue()));
}
}
的AccountService
public class AccountServiceImpl implements AccountService {
private LdapTemplate ldapTemplate;
@Autowired
public AccountServiceImpl(LdapTemplate ldapTemplate) {
this.ldapTemplate = ldapTemplate;
}
@Override
public Account retrieveAccount(String userId) {
LdapQuery query = query().base("ou=users").where("uid").is(userId);
List<Account> list = ldapTemplate.search(query,
new AccountMapper());
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
public class AccountMapper implements
AttributesMapper<Account> {
@Override
public Account mapFromAttributes(Attributes attrs)
throws NamingException {
Account account = new Account();
account.setEmail((String) attrs.get("mail").get());
account.setUserId((String) attrs.get("uid").get());
return account;
}
}
}
(离开Account类,因为它应该是自我解释的。)
如果我将mockLdapTemplate.search(query().base(anyString).where(anyString)
.is("userA"), (AttributesMapper) any);
替换为mockLdapTemplate.search((LdapQuery)withNotNull(), (AttributesMapper) any)
测试通过(这是我所期望的,但这或多或少告诉我问题在于LdapQuery参数)。
谢谢!
答案 0 :(得分:0)
您已经知道答案:期望值应记录为
mockLdapTemplate.search((LdapQuery)withNotNull(), (AttributesMapper) any)
因为这是从被测单元调用的唯一模拟方法。参数匹配“any”,“withNotNull()”等只能用于对模拟方法的调用,并且LdapQuery
未在测试中被模拟。