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

时间:2013-09-21 23:00:08

标签: java android unit-testing mocking powermock

我有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:package org.powermock.core.classloader.annotations不存在

的Maven:

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

1 个答案:

答案 0 :(得分:0)

您似乎缺少Maven依赖项。根据{{​​3}},注释由以下提供:

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