Java中的Mock/Stub超级构造函数调用,用于单元测试 [英] Mock/Stub super constructor invocation in Java for unit testing

查看:185
本文介绍了Java中的Mock/Stub超级构造函数调用,用于单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试使用Powermock模拟构造函数调用,但是它似乎不适用于super调用.我的测试:

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

我得到一个例外:

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

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

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?

推荐答案

直接从Powermocks文档.

然后可以在不调用EvilParent构造函数的情况下进行测试.

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

这篇关于Java中的Mock/Stub超级构造函数调用,用于单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆