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

我正在尝试编写单元测试用例以使用一些 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();

          });

       });


     } 


}


梵蒂冈之花
浏览 67回答 1
1回答

牧羊人nacy

基本上,您有一个在您执行请求时创建的注入器,并且使用该注入器是因为您使用requestInjection(this).&nbsp;这将覆盖您使用的任何类型的注入。具体来说,这就是正在发生的事情:Mockito 注入模拟。你用injector.injectMembers(this).所以不要在start方法中创建注入器:在适当的地方移动它,这取决于你使用的各种框架。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java