账号:Mockito 测试账号
Account: Mockito Test Account
我正在使用 Mockito 为 returns Account 对象的方法编写单元测试。
我正在创建一个新帐户如下:
Private Account testAccount = new Account("name", "type");
代码没有崩溃,但我在调试时总是遇到这个异常:
Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.accounts.Account.toString()
并且testAccount.name
和testAccount.type
总是null
。
有人可以告诉我我是否做错了什么,或者是否有适当的方法来模拟它并获得与初始化时定义的相同的帐户名称和类型?
一位同事发现我们必须对 Account 对象进行反射,因为它的字段定义为 final,因此您必须按以下方式进行:
Account account = new Account("MyAccount", "SomeType");
Field nameField = account.getClass().getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(account, "your value");
// Set whatever field you want to configure
Field typeField = account.getClass().getDeclaredField("type");
typeField.setAccessible(true);
typeField.set(account, "your value");
我正在使用 Mockito 为 returns Account 对象的方法编写单元测试。
我正在创建一个新帐户如下:
Private Account testAccount = new Account("name", "type");
代码没有崩溃,但我在调试时总是遇到这个异常:
Method threw 'java.lang.RuntimeException' exception. Cannot evaluate android.accounts.Account.toString()
并且testAccount.name
和testAccount.type
总是null
。
有人可以告诉我我是否做错了什么,或者是否有适当的方法来模拟它并获得与初始化时定义的相同的帐户名称和类型?
一位同事发现我们必须对 Account 对象进行反射,因为它的字段定义为 final,因此您必须按以下方式进行:
Account account = new Account("MyAccount", "SomeType");
Field nameField = account.getClass().getDeclaredField("name");
nameField.setAccessible(true);
nameField.set(account, "your value");
// Set whatever field you want to configure
Field typeField = account.getClass().getDeclaredField("type");
typeField.setAccessible(true);
typeField.set(account, "your value");