我正在使用 Mockito 为返回 Account 对象的方法编写单元测试。
我正在创建一个新帐户,如下所示:
Private Account testAccount = new Account("name", "type");
代码没有崩溃,但我在调试时总是遇到此异常:
方法抛出“java.lang.RuntimeException”异常。无法评估 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");
我猜你正在运行单元测试。 Account 类只能在单元测试运行时作为存根使用。如果您需要 Account 类,您必须在 Android 模拟器上运行测试(仪表测试)。另一种选择是从存根中模拟您需要的所有方法。