【问题标题】:Account: Mockito Test Account账户:Mockito 测试账户
【发布时间】:2018-08-23 22:42:50
【问题描述】:

我正在使用 Mockito 为返回 Account 对象的方法编写单元测试。

我正在创建一个新帐户,如下所示:

Private Account testAccount = new Account("name", "type");

代码没有崩溃,但我在调试时总是遇到这个异常:

方法抛出“java.lang.RuntimeException”异常。无法评估 android.accounts.Account.toString()

testAccount.nametestAccount.type 始终是null

谁能告诉我我做错了什么,或者是否有适当的方法来模拟它并获得与初始化时定义的相同的帐户名称和类型?

【问题讨论】:

    标签: android unit-testing mockito powermockito


    【解决方案1】:

    工作中的一位同事发现我们必须对 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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 2013-02-28
      • 2018-08-06
      相关资源
      最近更新 更多