为了账号安全,请及时绑定邮箱和手机立即绑定

如何在我的单元测试中使用 Mockito 或任何 Mocking 框架来模拟 Guice 注入?

如何在我的单元测试中使用 Mockito 或任何 Mocking 框架来模拟 Guice 注入?

梵蒂冈之花 2022-10-12 15:28:49
我正在尝试编写单元测试用例以使用一些 mockito 作为模拟框架来测试我的代码,在这之间我遇到了一个问题,我无法模拟我在测试类中使用 Google Guice 进行的注入。我尝试直接注入对象,它可以工作,但谷歌注入没有运气。class SomeClassToCreateWiskey{// Some Service@Inject@Named("dataCreation")DataCreation dataCreation;public apis(){    Injector injector = Guice.createInjector(new DataCreationModel());    injector.injectMembers(this);    int port = config().getInteger("http.port", 8080);    Router router = Router.router(vertx);    router.route("/api/getAll").handler(this::getAll);  }// getAll method will return some json result}测试上述 API 的测试类class SomeClassToCreateWiskeyTest{     @Mock     private DataCreation dataCreation;     // setting up before and after config     @Before     MockitoAnnotations.initMocks(this);       ......     @After       ......     @Test     public void testGetAll(){       Map<Integer, Whisky> dataSets = new LinkedHashMap<>();       Whisky w1 = new Whisky("Bowmore 15 Years Laimrig", "Scotland, Islay");       Whisky w2 = new Whisky("Talisker 57° kya h", "Scotland, Island");      Async async = context.async();      dataSets.put(w1.getId(), w1);      dataSets.put(w2.getId(), w2);      when(dataCreationDao.getData()).thenReturn(dataSets);      when(dataCreation.getData()).thenReturn(dataSets);      HttpClient client = vertx.createHttpClient();      client.getNow(port, "localhost", "/api/getAll", response -> {      response.bodyHandler(body -> {        System.out.println(body.toString());        client.close();        async.complete();          });       });     } }
查看完整描述

1 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

基本上,您有一个在您执行请求时创建的注入器,并且使用该注入器是因为您使用requestInjection(this). 这将覆盖您使用的任何类型的注入。

具体来说,这就是正在发生的事情:

  1. Mockito 注入模拟。

  2. 你用injector.injectMembers(this).

所以不要在start方法中创建注入器:在适当的地方移动它,这取决于你使用的各种框架。


查看完整回答
反对 回复 2022-10-12
  • 1 回答
  • 0 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信