java中stub的使用,Java中的Mock / Stub超级构造函数调用,用于单元测试

I want to unit-test my class with JUnit and EasyMock. It extends android.location.Location. But I am always getting Stub! exception because most of Android methods are not available in JVM runtime.

public class MyLocation extends Location {

public MyLocation(Location l) {

super(l);

}

public boolean methodUnderTest() {

return true;

}

}

I've tried to mock constructor invocation using Powermock, but it looks like it does not work for super calls. My test:

@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());

}

}

An exception I am getting:

java.lang.RuntimeException: Stub!

at android.location.Location.(Location.java:6)

Obviously the solution is to execute this test in Android runtime (i.e. start Android Simulator). But I don't like this approach because it takes quite a few time to start such test suite. Is there a way to stub super invocation or probably there's better approach in testing such implementations?

解决方案

Testing can then be done without invoking the EvilParent constructor.

@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());

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值