简体   繁体   English

在Robolectric测试中注入嘲笑

[英]Injecting mocks in a Robolectric test

I have to build a Robolectric test for a particular Activity that has a private field (a presenter). 我必须为具有私有字段(演示者)的特定Activity构建Robolectric测试。 In order to inject a mock into that field I used reflection, since the project I'm working on has no Dependency Injection framework. 为了将模拟注入到该字段中,我使用了反射,因为我正在处理的项目没有依赖注入框架。

My test setup is as follows: 我的测试设置如下:

MyActivityTest.java MyActivityTest.java

public class ConsumoViewTest {

@Mock
MvpConsumo.Presenter mockPresenter;

private MyActivity view;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    ActivityController<MyActivity> activityController =
        Robolectric.buildActivity(MyActivity.class);
    view = activityController.get();
    try {
        FieldUtils.writeField(view, "presenter", mockPresenter, true);
    } catch (IllegalAccessException e){
        //Exception handling
    }
    activityController.setup();
}

As part of my Activity setup, it creates and adds a Fragment and during OnAttach() the Fragment calls the getter for the presenter. 作为我的Activity设置的一部分,它创建并添加了一个Fragment ,在OnAttach()期间, Fragment调用演示者的getter。 Now, the thing I can't understand is that the Activity returns a real presenter instead of the mock I injected. 现在,我无法理解的是, Activity返回一个真正的演示者而不是我注入的模拟。 This real presenter eventually calls my real model and my real webservice which is obviously not ideal for testing. 这个真正的主持人最终称我的真实模型和我的真实网络服务显然不是测试的理想选择。

Does anyone now why my mock is being ignored on this scenario? 现在有人为什么我的模拟在这种情况下被忽略了?

After writing the question I realized what the problem was. 写完问题后,我意识到问题所在。 My reflection does work and the presenter is being initialized as a Mock, but I forgot that during Activity.OnCreate() the presenter is initialized as a real presenter, thus overriding the Mock I had injected previously. 我的反射确实有效,主持人被初始化为模拟,但我忘记了在Activity.OnCreate()期间,主持人被初始化为真正的主持人,从而覆盖了我先前注入过的模拟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM