我正在为一种方法编写单元测试,如果在我的 twilio 帐户上已经找到子帐户,则该方法返回 true。我正在尝试使用 Mockito 来模拟它,但在将 List 转换为 AccountList 时出现转换错误。我查看了 mockito 文档,但可能遗漏了一些东西。
这是测试:
@Mock
TwilioRestClient client;
@Mock
AccountList accountList;
@Mock
Iterator<Account> iterator;
@Mock
Account account;
@Test
public void testShouldReturnTrueIfAccountNameFound() {
final List<Account> list = Arrays.asList(account);
when(client.getAccounts()).thenReturn((AccountList) list);
when(account.getFriendlyName()).thenReturn("test");
when(accountList.iterator()).thenReturn(list.iterator());
MyTwilioAccountStore store = null;
store = new MyTwilioAccountStore(client);
Assert.assertTrue(store.subAccountExists("test"));
}
这就是我正在测试的方法。我在构造函数中注入了 TwilioRestClient。
/**
* class constructor
*
* @param client
*/
public MyTwilioAccountStore(TwilioRestClient client) {
fClient = client;
}
/**
* rest client getter
*
* @return RESTClient
*/
public TwilioRestClient getRestClient() {
return fClient;
}
/**
* Check if a sub account already exists
*
* @param friendlyName
* @return boolean
*/
public boolean subAccountExists(String friendlyName) {
// Build a filter for the AccountList
Map<String, String> params = new HashMap<String, String>();
params.put("FriendlyName", friendlyName);
AccountList accounts = getRestClient().getAccounts(params);
// Loop over accounts
// This is where I get NPE
for (Account account : accounts) {
if (account.getFriendlyName().equalsIgnoreCase(friendlyName)) {
return true;
}
}
return false;
}
这是 Twilio 源代码的 getAccounts:
/**
* Get all accounts. For more info: {@link <a
* href="http://www.twilio.com/docs/api/rest/account"
* >http://www.twilio.com/docs/api/rest/account</a>}
*
* @return the list of accounts.
*/
public AccountList getAccounts() {
return this.getAccounts(new HashMap<String, String>());
}
如何正确模拟 AccountList?