如何在 Android 中测试静态方法调用



我有一个Android活动,我想编写一个单元测试,该单元测试验证该活动是否onResume检查互联网是否可用。

public class MyActivity {
    @Override
    protected void onResume() {
        super.onResume();
        setContentView(R.layout.connect_to_server);
        // Internet availability check
        final IInternetAvailabilityChecker checker =  InternetAvailabilityChecker.create(this);
        if (!checker.isInternetAvailable())
        {
            Utils.showMessageBox(this, R.string.app_name,
                    R.string.internet_not_available);
            return;
        }

在测试中,我想验证MyActiviy.onResume是否调用了InternetAvailabilityChecker.create方法。

我该怎么做(使用任何与Android兼容的免费模拟框架)?

我尝试为此使用 PowerMock(请参阅下面的示例),但是当我尝试运行测试时,我收到类似 MockTest.java:7 的错误:包 org.powermock.core.classloader.annotations 不存在

专家:

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>${powermock.version}</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.10</version>
</dependency>

单元测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest( { InternetAvailabilityChecker.class })
public class MyActivityPowerMockTest {
    @Test
    @Ignore
    public void test()
    {
        final IInternetAvailabilityChecker checker = mock(IInternetAvailabilityChecker.class);
        when(checker.isInternetAvailable()).thenReturn(false);
        mockStatic(InternetAvailabilityChecker.class);
        expect(InternetAvailabilityChecker.create(any(Activity.class))).andReturn(checker);
        replay(InternetAvailabilityChecker.class);
        final MyActivity objectUnderTest = new MyActivity();
        objectUnderTest.onResume();
        // Verify that the method InternetAvailabilityChecker.create was called
        verify(InternetAvailabilityChecker.class); 
        // TODO: Verify that Utils.showMessageBox has been invoked
    }
}

您似乎缺少 Maven 依赖项。 根据此查询,注释由以下人员提供:

  • org.powermock/powermock-core
  • org.powermock/powermock-easymock-single-jar-release-full
  • org.powermock/powermock-mockito-single-jar-release-full

相关内容

  • 没有找到相关文章

最新更新