Robolectric阴影不工作 [英] Robolectric shadow not working

查看:121
本文介绍了Robolectric阴影不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想是 Robolectric 创建一个测试。我的目标是能够取代一类的功能(自带例如从图书馆,我不能修改code)从自定义的行为。

I'm trying to create a test with Robolectric. My goal is to be able to replace the functionality of one class (that comes for example from a library and I can't modify the code) from a custom behaviour.

我创造了这个小测试,模拟一下我想要做的:

I created this small test to simulate what I want to do:

@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowMessenger.class})
public class TestShadow {

    @Test
    public void testMessenger() {
        OriginalMessenger messenger = new OriginalMessenger();
        String message = messenger.getMessage();
        Assert.assertEquals("Shadow messenger", message);
    }

    public static class OriginalMessenger {

        public String getMessage() {
            return "Original messenger";
        }
    }

    @Implements(OriginalMessenger.class)
    public static class ShadowMessenger extends OriginalMessenger {

        @Implementation
        public String getMessage() {
            return "Shadow messenger";
        }
    }
}

在这个例子中, OriginalMessenger 的是,是在库中,并提供默认功能的类。而 ShadowMessenger 的是包含,我想只要我使用应用自定义行为类的 OriginalMessenger 的。

In the example, OriginalMessenger is the class that is in the library and provides a default functionality. And ShadowMessenger is the class that contains the custom behaviour that I want to apply whenever I use OriginalMessenger.

然而,当我运行它未能通过测试。的内容的的消息的是原始的使者。仿佛的 ShadowMessenger 的从未被使用过。

However when I run the test it fails. The content of message is "Original messenger". As if the ShadowMessenger was never used.

我是什么做错了吗?

推荐答案

原装只能影子机器人类。但是,使用自定义robolectric测试运行,你也可以阴影自己的类。

Original you can only shadow android classes. But with a custom robolectric test runner you can also shadow your own classes.

Robolectric 3.0

Robolectric 3.0

@Override
public InstrumentationConfiguration createClassLoaderConfig() {
    InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
    builder.addInstrumentedClass(OriginalMessenger.class.getName());
    return builder.build();
}

Robolectric 2.4

Robolectric 2.4

@Override
protected ClassLoader createRobolectricClassLoader(Setup setup, SdkConfig sdkConfig) {
    return super.createRobolectricClassLoader(new ExtraShadows(setup), sdkConfig);
}

class ExtraShadows extends Setup {
    private Setup setup;

    public ExtraShadows(Setup setup) {
        this.setup = setup;
    }

    public boolean shouldInstrument(ClassInfo classInfo) {
        boolean shoudInstrument = setup.shouldInstrument(classInfo);
        return shoudInstrument
                || classInfo.getName().equals(OriginalMessenger.class.getName());
    }
}

例如项目 https://github.com/nenick/android-gradle-template/

这篇关于Robolectric阴影不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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