我试图创建在Verticle中自动装配的类的模拟实例,但是我将其作为空值获取。对于同步代码,有效的方法对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());
}
});
}
}
如果我不使用自动装配的实例来调用获取日期的方法,则“测试用例”就可以很好地工作。但是,如果使用了它(我必须这样做才能获取数据),则在尝试使用serviceExecutor对象作为模拟时,它将在MyVerticle-> getSomeData()方法中提供NPE。这种方法对于同步代码流非常有效,但对于Vert.x似乎无济于事。因此,在这里需要帮助来模拟Verticle中自动装配的实例“ serviceExecutor”。
答案 0 :(得分:1)
在MyVerticle中添加构造函数
public MyVerticle(ApplicationContext context) {
context.getAutowireCapableBeanFactory().autowireBean(this);
}
并部署您的vertex.deployVerticle(新的MyVerticle(上下文),...)
我在部署verticle时具有应用程序上下文,这就是我在构造函数中传递的内容。检查是否适合您。