1

我有一个 Android 活动,我想编写一个单元测试,以验证在onResume活动中检查 Internet 是否可用。

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: package org.powermock.core.classloader.annotations does not exist 之类的错误。

马文:

<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
    }
}
4

1 回答 1

0

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

  • org.powermock / powermock-core
  • org.powermock / powermock-easymock-single-jar-release-full
  • org.powermock / powermock-mockito-single-jar-release-full
于 2013-09-22T01:40:07.777 回答