如何在Vert.x中创建Autowired组件的模拟实例 [英] How to create mock instance of Autowired component in Vert.x

查看:161
本文介绍了如何在Vert.x中创建Autowired组件的模拟实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建类的模拟实例,该类在Verticle内部为autowired,但是我将其作为空值获取.对于同步代码,有效的方式对于Vert.x似乎没有用.

I am trying to create mock instance of the class which is autowired inside Verticle but I am getting it as a null. For synchronous code the way which works is looking not useful for Vert.x.

顶点为:

    @Component
    public class MyVerticle extends AbstractVerticle{

    @Autowired
    private ServiceExecutor serviceExecutor;

    @Override
    public void start() throws Exception {
        super.start();
        vertx.eventBus().<String>consumer("address.xyz").handler(handleRequest());
    }

    private Handler<Message<String>> handleRequest() {
        return msg -> {
            getSomeData(msg.body().toString())
            .setHandler(ar -> {
                if(ar.succeeded()){
                    msg.reply(ar.result());
                }else{
                    msg.reply(ar.cause().getMessage());
                }
             });
        };
    }

    private Future<String> getSomeData(String inputJson) {
        Promise<String> promise = Promise.promise();
        String data = serviceExecutor.executeSomeService(inputJson); // Getting NPE here. serviceExecutor is coming as null when trying to create mock of it using Mockito.when.
        promise.complete(data);
        return promise.future();    
     }
  }

从属组件是:

@Component
public class ServiceExecutor {

    public String executeSomeService(String input){
        return "Returning Data";
    }
}

测试用例是:

import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;

@RunWith(VertxUnitRunner.class)
public class MyVerticleTest {

    @Mock
    private ServiceExecutor serviceExecutor;

    private Vertx vertx;

    @Before
    public void setup(TestContext ctx){
        MockitoAnnotations.initMocks(this);
        Async async = ctx.async();
        this.vertx = Vertx.vertx();
        vertx.deployVerticle(MyVerticle.class.getName(), h -> {
            if(h.succeeded()){
                async.complete();
            }else{
                ctx.fail();
            }
        });
    }

    @Test
    public void test_consumption(TestContext ctx) {
        Async async = ctx.async();
        when(serviceExecutor.executeSomeService(Mockito.anyString())).thenReturn("Returning Data");
        vertx.eventBus().request("address.xyz","message", h ->{
            if(h.succeeded()){
                ctx.assertEquals("Returning Data",h.result().body().toString());
                async.complete();
            }else{
                ctx.fail(h.cause());
            }
        });
    }
}

如果我不使用autowired实例调用方法来获取日期,

上述测试用例"就可以很好地工作.但是,如果使用它(我必须这样做才能获取数据),则在尝试使用serviceExecutor对象作为模拟对象时,它会在MyVerticle->getSomeData()方法处提供NPE.这种方法对于同步代码流非常有效,但对于Vert.x似乎无济于事.因此,在这里需要帮助来模拟Verticle中的autowired实例serviceExecutor.

Above Test Case works well if I don't use autowired instance to call a method to get the date. But if used it (which I must do to get the data), it is giving NPE at MyVerticle->getSomeData() method when trying to use serviceExecutor object as a mock. This approach works very well for Synchronous code flow but for Vert.x looks like it won't help. So need help here to mock the autowired instance serviceExecutor inside Verticle.

推荐答案

在MyVerticle中添加构造函数

Add a constructor in your MyVerticle

public MyVerticle(ApplicationContext context) {
    context.getAutowireCapableBeanFactory().autowireBean(this);
}

并部署vertex.deployVerticle(新的MyVerticle(上下文),...)之类的顶点...

and deploy your verticle something like vertx.deployVerticle(new MyVerticle(context),...

我在部署verticle时具有应用程序上下文,这就是我在构造函数中传递的内容.检查它是否适合您.

I have application context while deploying the verticle and thats what I am passing in the constructor. Check if this works for you.

这篇关于如何在Vert.x中创建Autowired组件的模拟实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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