用Java进行Mock / Stub超级构造函数调用以进行单元测试

时间:2013-10-08 18:19:34

标签: java android unit-testing junit

我想用JUnitEasyMock对我的班级进行单元测试。它扩展了android.location.Location。但我总是得到Stub!异常,因为大多数Android方法在JVM运行时都不可用。

public class MyLocation extends Location {
    public MyLocation(Location l) {
        super(l);
    }

    public boolean methodUnderTest() {
        return true;
    }
}

我尝试使用Powermock模拟构造函数调用,但看起来它对super调用不起作用。我的测试:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Location.class)
public class MyLocationTest {
    @Test
    public void methodUnderTestReturnsTrue() throws Exception {
        Location locationMock = EasyMock.createMock(Location.class);
        expectNew(Location.class, Location.class).andReturn(locationMock);
        MyLocation myLocation = new MyLocation(locationMock);
        assertTrue(myLocation.methodUnderTest());
    }
}

我得到的例外:

java.lang.RuntimeException: Stub!
    at android.location.Location.<init>(Location.java:6)

显然,解决方案是在Android运行时执行此测试(即启动Android模拟器)。但我不喜欢这种方法,因为启动这样的测试套件需要花费很多时间。有没有办法存根super调用,或者可能有更好的方法来测试这样的实现?

1 个答案:

答案 0 :(得分:1)

Taken straight from the Powermocks documentation.

然后可以在不调用EvilParent构造函数的情况下完成测试。

@RunWith(PowerMockRunner.class)
@PrepareForTest(ExampleWithEvilParent.class)
public class ExampleWithEvilParentTest {

        @Test
        public void testSuppressConstructorOfEvilParent() throws Exception {
                suppress(constructor(EvilParent.class));
                final String message = "myMessage";
                ExampleWithEvilParent tested = new ExampleWithEvilParent(message);
                assertEquals(message, tested.getMessage());
        }
}