【问题标题】:Simple Test Mockito on Android is failingAndroid 上的简单测试 Mockito 失败
【发布时间】:2015-07-06 13:29:50
【问题描述】:

谁能告诉我为什么这个测试失败和/或如何让测试运行?

测试正确运行,直到最后一个断言。

@RunWith(MockitoJUnitRunner.class)
public class AccountHelpTest {

    @Mock
    AccountManager accountManager;

    public class AccountHelp {
        public AccountManager accountManager;
        public Account[] getAccounts(String type) {
            return accountManager.getAccountsByType(type);
        }
    }

    @Test
    public void account() {
        AccountHelp ah = new AccountHelp();
        ah.accountManager = accountManager;

        when(accountManager.getAccountsByType(anyString())).thenReturn(new Account[]{new Account("name", "type")});

        Account[] types = ah.getAccounts("type");

        Assert.assertNotNull(types);

        Assert.assertEquals(1, types.length);

        Assert.assertEquals("name", types[0].name);
    }
}

我可以把它分解成这个问题:

Account account = new Account("name", "test");
Assert.assertEquals("name", account.name);

这是失败的! (它是一个 JUnit4 测试,而不是一个仪器测试)

【问题讨论】:

标签: android mockito junit4


【解决方案1】:

事实证明,Android Studio provides a special android.jar 用于测试,这使得 Mockito 能够工作。 这个 jar 中的所有类都是某种 dummy 类,这就是测试失败的原因。

作为一种解决方案(取决于您要测试的内容),您可以创建自己的要使用的类的实现。在我的课堂上是这样的:

package android.accounts;

public class Account {
    public final String type;
    public final String name;

    public Account(String name, String type) {
        this.name = name;
        this.type = type;
    }
}

创建这个并再次执行测试后,测试成功。

【讨论】:

    【解决方案2】:

    正如 Unicate 所说,Android Studio 提供了一个 android.jar,其中所有方法都是存根。 Robolectric 是通过生成替代 Android 内置插件的工作模拟类来处理这个问题的。他们将ShadowAccountManager 替换为AccountManager

    就我个人而言,我发现他们新版本的文档非常稀少,但也许你的运气会比我好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多