我正在尝试创建autowired
内部类的模拟实例,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());
}
});
}
}
autowired
如果我不使用实例调用方法来获取日期,上面的测试用例效果很好。但是如果使用它(我必须这样做才能获取数据),它会MyVerticle->getSomeData()
在尝试将serviceExecutor
对象用作模拟对象时给出 NPE at 方法。这种方法非常适用于同步代码流,但Vert.x
看起来无济于事。所以这里需要帮助来模拟里面的autowired
实例。serviceExecutor
Verticle